import React, { useState, useEffect } from 'react';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Badge } from '@/components/ui/badge';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { Textarea } from '@/components/ui/textarea';
import { useToast } from '@/hooks/use-toast';
import { useTokenExpiry, setGlobalTokenExpiryHandler } from '@/hooks/use-token-expiry';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from '@/components/ui/dialog';
import { Label } from '@/components/ui/label';
import {
  MessageSquare,
  Search,
  Filter,
  Plus,
  Send,
  Bot,
  User,
  Clock,
  Star,
  MoreVertical,
  Download,
  Trash2,
  Eye,
  TrendingUp,
  Settings,
  RefreshCw,
  Loader2,
  X,
  Archive,
  ArchiveRestore,
  CheckSquare,
  Square,
  Edit,
  Tag,
  Calendar,
  Users,
  BarChart3,
  Play,
  Pause,
  Save,
  Brain
} from 'lucide-react';
import { api, ChatSession as ApiChatSession, ChatMessage as ApiChatMessage } from '@/lib/api';

export default function ChatManagementPage() {
  // Toast hook
  const { toast } = useToast();
  
  // Token过期处理hook
  const { handleTokenExpiry, ReauthDialogComponent } = useTokenExpiry();
  
  // 会话和消息状态
  const [sessions, setSessions] = useState<ApiChatSession[]>([]);
  const [selectedSession, setSelectedSession] = useState<ApiChatSession | null>(null);
  const [messages, setMessages] = useState<ApiChatMessage[]>([]);
  const [newMessage, setNewMessage] = useState('');
  const [searchTerm, setSearchTerm] = useState('');
  const [statusFilter, setStatusFilter] = useState('all');
  const [loading, setLoading] = useState(true);
  const [sendingMessage, setSendingMessage] = useState(false);
  const [newSessionTitle, setNewSessionTitle] = useState('');
  const [creatingSession, setCreatingSession] = useState(false);
  const [showNewSessionDialog, setShowNewSessionDialog] = useState(false);
  
  // AI响应状态
  const [aiThinking, setAiThinking] = useState(false);
  const [aiThinkingTime, setAiThinkingTime] = useState(0);
  const [aiThinkingTimer, setAiThinkingTimer] = useState<NodeJS.Timeout | null>(null);
  const [streamingMessage, setStreamingMessage] = useState('');
  const [isStreaming, setIsStreaming] = useState(false);
  const [streamingSessionId, setStreamingSessionId] = useState<string | null>(null);
  const [connectionStatus, setConnectionStatus] = useState<'disconnected' | 'connecting' | 'connected' | 'error'>('disconnected');
  const [errorInfo, setErrorInfo] = useState(''); // 添加errorinfo状态
  const [messageSaveStatus, setMessageSaveStatus] = useState<'none' | 'saving' | 'saved' | 'failed'>('none');
  
  // 批量操作状态
  const [selectedSessions, setSelectedSessions] = useState<string[]>([]);
  const [bulkActionLoading, setBulkActionLoading] = useState(false);
  const [showBulkActions, setShowBulkActions] = useState(false);
  
  // 会话编辑状态
  const [editingSession, setEditingSession] = useState<string | null>(null);
  const [editTitle, setEditTitle] = useState('');
  
  // 归档状态
  const [showArchived, setShowArchived] = useState(false);
  
  // 增强搜索和过滤状态
  const [contentSearch, setContentSearch] = useState(''); // 消息内容搜索
  const [dateRange, setDateRange] = useState('all'); // 时间范围过滤
  const [userTypeFilter, setUserTypeFilter] = useState('all'); // 用户类型过滤
  const [messageCountFilter, setMessageCountFilter] = useState('all'); // 消息数量过滤
  const [showAdvancedFilters, setShowAdvancedFilters] = useState(false);
  
  // 导出功能状态
  const [exportLoading, setExportLoading] = useState(false);
  const [showExportDialog, setShowExportDialog] = useState(false);
  const [exportFormat, setExportFormat] = useState<'text' | 'pdf'>('text');
  const [exportSessionId, setExportSessionId] = useState<string | null>(null);

  // 聊天质量评估和反馈系统状态
  const [showFeedbackDialog, setShowFeedbackDialog] = useState(false);
  const [feedbackSessionId, setFeedbackSessionId] = useState<string | null>(null);
  const [feedbackMessageId, setFeedbackMessageId] = useState<string | null>(null);
  const [rating, setRating] = useState<number>(0);
  const [feedbackText, setFeedbackText] = useState('');
  const [feedbackCategory, setFeedbackCategory] = useState<'helpful' | 'accurate' | 'relevant' | 'clear' | 'other'>('helpful');
  const [submittingFeedback, setSubmittingFeedback] = useState(false);
  const [messageRatings, setMessageRatings] = useState<Record<string, number>>({});
  
  // 多用户聊天会话监控状态
  const [onlineUsers, setOnlineUsers] = useState<Array<{id: string, name: string, status: 'online' | 'away' | 'busy', lastSeen: string, avatar?: string}>>([]);
  const [userSessions, setUserSessions] = useState<Record<string, string[]>>({});
  const [showUserMonitor, setShowUserMonitor] = useState(false);
  const [selectedUser, setSelectedUser] = useState<string | null>(null);
  const [sessionAssignments, setSessionAssignments] = useState<Record<string, string>>({});
  const [showAssignDialog, setShowAssignDialog] = useState(false);
  const [assignSessionId, setAssignSessionId] = useState<string | null>(null);
  const [userWorkload, setUserWorkload] = useState<Record<string, number>>({});

  // 聊天机器人配置和训练状态
  const [showBotConfig, setShowBotConfig] = useState(false);
  const [botConfigs, setBotConfigs] = useState<Array<{
    id: string;
    name: string;
    description: string;
    model: string;
    temperature: number;
    maxTokens: number;
    systemPrompt: string;
    isActive: boolean;
    createdAt: string;
    lastTrained?: string;
    trainingStatus: 'idle' | 'training' | 'completed' | 'error';
  }>>([]);
  const [selectedBotConfig, setSelectedBotConfig] = useState<string | null>(null);
  const [showConfigDialog, setShowConfigDialog] = useState(false);
  const [showTrainingDialog, setShowTrainingDialog] = useState(false);
  const [trainingData, setTrainingData] = useState('');
  const [trainingStatus, setTrainingStatus] = useState<'idle' | 'training' | 'completed' | 'error'>('idle');
  const [trainingProgress, setTrainingProgress] = useState(0);
  const [configForm, setConfigForm] = useState({
    name: '',
    description: '',
    model: 'gpt-3.5-turbo',
    temperature: 0.7,
    maxTokens: 2048,
    systemPrompt: '',
    isActive: true
  });

  // 聊天数据统计和分析状态
  const [showAnalytics, setShowAnalytics] = useState(false);
  const [analyticsData, setAnalyticsData] = useState({
    totalSessions: 0,
    totalMessages: 0,
    avgSessionLength: 0,
    avgResponseTime: 0,
    userSatisfaction: 0,
    topTopics: [],
    dailyStats: [],
    weeklyStats: [],
    monthlyStats: []
  });
  const [analyticsTimeRange, setAnalyticsTimeRange] = useState('7d');
  const [analyticsLoading, setAnalyticsLoading] = useState(false);
  const [exportDateRange, setExportDateRange] = useState({
    start: '',
    end: ''
  });

  // 敏感词过滤和内容审核状态
  const [showContentFilter, setShowContentFilter] = useState(false);
  const [sensitiveWords, setSensitiveWords] = useState<string[]>(['违法', '暴力', '色情', '赌博', '毒品']);
  const [filterRules, setFilterRules] = useState({
    enabled: true,
    strictMode: false,
    autoBlock: true,
    notifyAdmin: true
  });
  const [auditLogs, setAuditLogs] = useState<any[]>([]);
  const [showAuditDialog, setShowAuditDialog] = useState(false);
  const [newSensitiveWord, setNewSensitiveWord] = useState('');
  const [auditLoading, setAuditLoading] = useState(false);
  const [filterStats, setFilterStats] = useState({
    totalFiltered: 0,
    todayFiltered: 0,
    blockedMessages: 0,
    warningMessages: 0,
    passRate: 95
  });

  // 标签和分类管理相关状态
  const [showTagManager, setShowTagManager] = useState(false);
  const [availableTags, setAvailableTags] = useState<string[]>(['工作', '学习', '娱乐', '技术支持', '产品咨询', '投诉建议']);
  const [availableCategories, setAvailableCategories] = useState<string[]>(['客服', '销售', '技术', '市场', '其他']);
  const [newTag, setNewTag] = useState('');
  const [newCategory, setNewCategory] = useState('');
  const [tagFilter, setTagFilter] = useState<string[]>([]);
  const [categoryFilter, setCategoryFilter] = useState<string[]>([]);
  const [showTagDialog, setShowTagDialog] = useState(false);
  const [selectedSessionForTag, setSelectedSessionForTag] = useState<string | null>(null);
  const [sessionTags, setSessionTags] = useState<{[key: string]: string[]}>({});
  const [sessionCategories, setSessionCategories] = useState<{[key: string]: string}>({});
  const [tagStats, setTagStats] = useState<{[key: string]: number}>({});
  const [categoryStats, setCategoryStats] = useState<{[key: string]: number}>({});

  // 加载聊天会话列表
  const loadSessions = async () => {
    try {
      setLoading(true);
      const sessionsData = await api.getChatSessions();
      setSessions(sessionsData);
      
      if (sessionsData.length > 0 && !selectedSession) {
        setSelectedSession(sessionsData[0]);
      }
    } catch (error) {
      console.error('加载聊天会话失败:', error);
      toast({
        title: '加载失败',
        description: '无法加载聊天会话列表',
        variant: 'destructive'
      });
    } finally {
      setLoading(false);
    }
  };

  // 加载聊天消息 - 总是从API获取最新数据
  const loadMessages = async (sessionId: string): Promise<void> => {
    try {
      const messagesData = await api.getChatMessages(sessionId);
      
      // 确保只有当前选中的会话才设置消息，避免异步加载导致的错乱
      if (selectedSession?.session_id === sessionId) {
        setMessages(messagesData);
        console.log(`消息加载完成，共 ${messagesData.length} 条消息`);
      }
    } catch (error) {
      console.error('加载聊天消息失败:', error);
      toast({
        title: '加载失败',
        description: '无法加载聊天消息',
        variant: 'destructive'
      });
      // 如果加载失败，设置为空数组
      if (selectedSession?.session_id === sessionId) {
        setMessages([]);
      }
      throw error; // 重新抛出错误以便调用者处理
    }
  };

  // 创建新会话
  const handleCreateSession = async () => {
    if (!newSessionTitle.trim()) return;

    try {
      setCreatingSession(true);
      const newSession = await api.createChatSession(newSessionTitle);
      setSessions(prev => [newSession, ...prev]);
      setSelectedSession(newSession);
      setNewSessionTitle('');
      setShowNewSessionDialog(false);
    } catch (error) {
      console.error('创建会话失败:', error);
      alert('创建会话失败，请稍后重试');
    } finally {
      setCreatingSession(false);
    }
  };

  // 删除会话
  const handleDeleteSession = async (sessionId: string) => {
    if (!confirm('确定要删除这个对话吗？此操作不可恢复。')) {
      return;
    }

    try {
      // 使用session_id而不是数字id来调用删除API
      await api.deleteChatSession(sessionId);
      setSessions(prev => prev.filter(s => s.session_id !== sessionId));
      
      // 如果删除的是当前选中的会话，清空选中状态
      if (selectedSession?.session_id === sessionId) {
        setSelectedSession(null);
        setMessages([]);
      }
      
      alert('对话删除成功');
    } catch (error) {
      console.error('删除会话失败:', error);
      alert('删除会话失败，请稍后重试');
    }
  };

  // 归档会话
  const handleArchiveSession = async (sessionId: string) => {
    try {
      const session = sessions.find(s => s.session_id === sessionId);
      if (!session) return;
      
      const newStatus = session.status === 'archived' ? 'active' : 'archived';
      // 这里应该调用API更新会话状态，暂时使用本地状态模拟
      setSessions(prev => prev.map(s => 
        s.session_id === sessionId 
          ? { ...s, status: newStatus }
          : s
      ));
      
      alert(newStatus === 'archived' ? '对话已归档' : '对话已恢复');
    } catch (error) {
      console.error('归档会话失败:', error);
      alert('操作失败，请稍后重试');
    }
  };

  // 编辑会话标题
  const handleEditSession = async (sessionId: string, newTitle: string) => {
    if (!newTitle.trim()) return;
    
    try {
      // 这里应该调用API更新会话标题，暂时使用本地状态模拟
      setSessions(prev => prev.map(s => 
        s.session_id === sessionId 
          ? { ...s, title: newTitle }
          : s
      ));
      
      setEditingSession(null);
      setEditTitle('');
      alert('标题更新成功');
    } catch (error) {
      console.error('更新标题失败:', error);
      alert('更新失败，请稍后重试');
    }
  };

  // 批量选择会话
  const handleSelectSession = (sessionId: string) => {
    setSelectedSessions(prev => 
      prev.includes(sessionId)
        ? prev.filter(id => id !== sessionId)
        : [...prev, sessionId]
    );
  };

  // 全选/取消全选
  const handleSelectAll = () => {
    const visibleSessionIds = filteredSessions.map(s => s.session_id);
    if (selectedSessions.length === visibleSessionIds.length) {
      setSelectedSessions([]);
    } else {
      setSelectedSessions(visibleSessionIds);
    }
  };

  // 批量删除
  const handleBulkDelete = async () => {
    if (selectedSessions.length === 0) return;
    
    if (!confirm(`确定要删除选中的 ${selectedSessions.length} 个对话吗？此操作不可恢复。`)) {
      return;
    }

    try {
      setBulkActionLoading(true);
      
      // 批量删除API调用
      for (const sessionId of selectedSessions) {
        await api.deleteChatSession(sessionId);
      }
      
      setSessions(prev => prev.filter(s => !selectedSessions.includes(s.session_id)));
      setSelectedSessions([]);
      
      // 如果当前选中的会话被删除，清空选中状态
      if (selectedSession && selectedSessions.includes(selectedSession.session_id)) {
        setSelectedSession(null);
        setMessages([]);
      }
      
      alert('批量删除成功');
    } catch (error) {
      console.error('批量删除失败:', error);
      alert('批量删除失败，请稍后重试');
    } finally {
      setBulkActionLoading(false);
    }
  };

  // 批量归档
  const handleBulkArchive = async () => {
    if (selectedSessions.length === 0) return;
    
    try {
      setBulkActionLoading(true);
      
      // 批量归档API调用（暂时使用本地状态模拟）
      setSessions(prev => prev.map(s => 
        selectedSessions.includes(s.session_id)
          ? { ...s, status: s.status === 'archived' ? 'active' : 'archived' }
          : s
      ));
      
      setSelectedSessions([]);
      alert('批量操作成功');
    } catch (error) {
      console.error('批量归档失败:', error);
      alert('批量操作失败，请稍后重试');
    } finally {
      setBulkActionLoading(false);
    }
  };
  
  // 搜索消息内容
  const searchInMessages = async (sessionId: string, searchTerm: string): Promise<boolean> => {
    try {
      const messages = await api.getChatMessages(sessionId);
      return messages.some(message => 
        message.content.toLowerCase().includes(searchTerm.toLowerCase())
      );
    } catch (error) {
      console.error('搜索消息内容失败:', error);
      return false;
    }
  };
  
  // 清空所有过滤器
  const clearAllFilters = () => {
    setSearchTerm('');
    setContentSearch('');
    setStatusFilter('all');
    setDateRange('all');
    setMessageCountFilter('all');
    setShowArchived(false);
  };
  
  // 导出聊天记录为文本格式
  const exportToText = async (sessionId: string) => {
    try {
      setExportLoading(true);
      
      // 获取会话信息
      const session = sessions.find(s => s.session_id === sessionId);
      if (!session) {
        throw new Error('会话不存在');
      }
      
      // 获取会话消息
      const sessionMessages = messages.filter(msg => msg.session_id === sessionId);
      
      // 生成文本内容
      let textContent = `聊天记录导出\n`;
      textContent += `会话标题: ${session.title}\n`;
      textContent += `创建时间: ${new Date(session.created_at).toLocaleString()}\n`;
      textContent += `状态: ${session.status}\n`;
      textContent += `消息数量: ${sessionMessages.length}\n`;
      textContent += `\n${'='.repeat(50)}\n\n`;
      
      sessionMessages.forEach((message, index) => {
        const timestamp = new Date(message.created_at).toLocaleString();
        const sender = message.sender_type === 'user' ? '用户' : 'AI助手';
        textContent += `[${index + 1}] ${sender} (${timestamp}):\n`;
        textContent += `${message.content}\n\n`;
      });
      
      // 创建下载链接
      const blob = new Blob([textContent], { type: 'text/plain;charset=utf-8' });
      const url = URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      link.download = `chat_${session.title}_${new Date().toISOString().split('T')[0]}.txt`;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      URL.revokeObjectURL(url);
      
    } catch (error) {
      console.error('导出文本失败:', error);
      alert('导出失败，请重试');
    } finally {
      setExportLoading(false);
    }
  };
  
  // 导出聊天记录为PDF格式
  const exportToPDF = async (sessionId: string) => {
    try {
      setExportLoading(true);
      
      // 获取会话信息
      const session = sessions.find(s => s.session_id === sessionId);
      if (!session) {
        throw new Error('会话不存在');
      }
      
      // 获取会话消息
      const sessionMessages = messages.filter(msg => msg.session_id === sessionId);
      
      // 动态导入jsPDF
      const { jsPDF } = await import('jspdf');
      
      // 创建PDF文档
      const doc = new jsPDF();
      
      // 设置字体（支持中文）
      doc.setFont('helvetica');
      
      // 添加标题
      doc.setFontSize(16);
      doc.text('聊天记录导出', 20, 20);
      
      // 添加会话信息
      doc.setFontSize(12);
      let yPosition = 40;
      doc.text(`会话标题: ${session.title}`, 20, yPosition);
      yPosition += 10;
      doc.text(`创建时间: ${new Date(session.created_at).toLocaleString()}`, 20, yPosition);
      yPosition += 10;
      doc.text(`状态: ${session.status}`, 20, yPosition);
      yPosition += 10;
      doc.text(`消息数量: ${sessionMessages.length}`, 20, yPosition);
      yPosition += 20;
      
      // 添加分隔线
      doc.line(20, yPosition, 190, yPosition);
      yPosition += 15;
      
      // 添加消息内容
      sessionMessages.forEach((message, index) => {
        // 检查是否需要换页
        if (yPosition > 250) {
          doc.addPage();
          yPosition = 20;
        }
        
        const timestamp = new Date(message.created_at).toLocaleString();
        const sender = message.sender_type === 'user' ? '用户' : 'AI助手';
        
        // 添加消息头
        doc.setFontSize(10);
        doc.text(`[${index + 1}] ${sender} (${timestamp}):`, 20, yPosition);
        yPosition += 8;
        
        // 添加消息内容（处理长文本换行）
        doc.setFontSize(9);
        const lines = doc.splitTextToSize(message.content, 170);
        doc.text(lines, 20, yPosition);
        yPosition += lines.length * 5 + 10;
      });
      
      // 保存PDF
      doc.save(`chat_${session.title}_${new Date().toISOString().split('T')[0]}.pdf`);
      
    } catch (error) {
      console.error('导出PDF失败:', error);
      alert('导出PDF失败，请确保已安装相关依赖');
    } finally {
      setExportLoading(false);
    }
  };
  
  // 处理导出
  const handleExport = async () => {
    if (!exportSessionId) return;
    
    if (exportFormat === 'txt') {
      await exportToText(exportSessionId);
    } else {
      await exportToPDF(exportSessionId);
    }
    
    setShowExportDialog(false);
    setExportSessionId(null);
  };
  
  // 打开导出对话框
  const openExportDialog = (sessionId: string) => {
    setExportSessionId(sessionId);
    setShowExportDialog(true);
  };

  // 打开反馈对话框
  const openFeedbackDialog = (sessionId: string, messageId?: string) => {
    setFeedbackSessionId(sessionId);
    setFeedbackMessageId(messageId || null);
    setRating(0);
    setFeedbackText('');
    setFeedbackCategory('helpful');
    setShowFeedbackDialog(true);
  };

  // 提交反馈
  const submitFeedback = async () => {
    if (!feedbackSessionId || rating === 0) {
      toast({
        title: "请选择评分",
        variant: "destructive"
      });
      return;
    }

    setSubmittingFeedback(true);
    try {
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 1000));
      
      // 保存评分到本地状态
      if (feedbackMessageId) {
        setMessageRatings(prev => ({
          ...prev,
          [feedbackMessageId]: rating
        }));
      }

      toast({
        title: "反馈提交成功",
        description: "感谢您的评价！"
      });
      setShowFeedbackDialog(false);
      setRating(0);
      setFeedbackText('');
      setFeedbackCategory('');
    } catch (error) {
      console.error('提交反馈失败:', error);
      toast({
        title: "提交反馈失败",
        description: "请稍后重试",
        variant: "destructive"
      });
    } finally {
      setSubmittingFeedback(false);
    }
  };

  // 快速评分（点击星星）
  const quickRate = async (messageId: string, rating: number) => {
    try {
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 300));
      
      setMessageRatings(prev => ({
        ...prev,
        [messageId]: rating
      }));
      
      toast({
        title: "评分成功",
        description: `已评分 ${rating} 星`
      });
    } catch (error) {
      console.error('评分失败:', error);
      toast({
        title: "评分失败",
        description: "请稍后重试",
        variant: "destructive"
      });
    }
  };
  
  // 加载在线用户列表
  const loadOnlineUsers = async () => {
    try {
      // 模拟API调用获取在线用户
      const mockUsers = [
        { id: 'user1', name: '张三', status: 'online' as const, lastSeen: new Date().toISOString(), avatar: '/avatars/user1.jpg' },
        { id: 'user2', name: '李四', status: 'away' as const, lastSeen: new Date(Date.now() - 300000).toISOString(), avatar: '/avatars/user2.jpg' },
        { id: 'user3', name: '王五', status: 'busy' as const, lastSeen: new Date(Date.now() - 600000).toISOString(), avatar: '/avatars/user3.jpg' },
        { id: 'user4', name: '赵六', status: 'online' as const, lastSeen: new Date().toISOString(), avatar: '/avatars/user4.jpg' }
      ];
      setOnlineUsers(mockUsers);
      
      // 模拟用户工作负载
      const workload = {
        'user1': 3,
        'user2': 1,
        'user3': 5,
        'user4': 2
      };
      setUserWorkload(workload);
      
      // 模拟会话分配
      const assignments = {
        'session1': 'user1',
        'session2': 'user3',
        'session3': 'user4'
      };
      setSessionAssignments(assignments);
      
    } catch (error) {
      console.error('加载在线用户失败:', error);
    }
  };
  
  // 分配会话给用户
  const assignSessionToUser = async (sessionId: string, userId: string) => {
    try {
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 500));
      
      setSessionAssignments(prev => ({
        ...prev,
        [sessionId]: userId
      }));
      
      // 更新用户工作负载
      setUserWorkload(prev => ({
        ...prev,
        [userId]: (prev[userId] || 0) + 1
      }));
      
      toast({
        title: "分配成功",
        description: `会话已分配给 ${onlineUsers.find(u => u.id === userId)?.name}`
      });
      
      setShowAssignDialog(false);
      setAssignSessionId(null);
    } catch (error) {
      console.error('分配会话失败:', error);
      toast({
        title: "分配失败",
        description: "请稍后重试",
        variant: "destructive"
      });
    }
  };
  
  // 打开分配对话框
  const openAssignDialog = (sessionId: string) => {
    setAssignSessionId(sessionId);
    setShowAssignDialog(true);
  };
  
  // 获取用户状态颜色
  const getUserStatusColor = (status: string) => {
    switch (status) {
      case 'online': return 'bg-green-500';
      case 'away': return 'bg-yellow-500';
      case 'busy': return 'bg-red-500';
      default: return 'bg-gray-500';
    }
  };
  
  // 获取用户状态文本
  const getUserStatusText = (status: string) => {
    switch (status) {
      case 'online': return '在线';
      case 'away': return '离开';
      case 'busy': return '忙碌';
      default: return '离线';
    }
  };

  // 加载机器人配置列表
  const loadBotConfigs = async () => {
    try {
      // 模拟加载机器人配置数据
      const mockConfigs = [
        {
          id: 'bot-1',
          name: '客服助手',
          description: '专业的客服聊天机器人，擅长处理用户咨询',
          model: 'gpt-3.5-turbo',
          temperature: 0.7,
          maxTokens: 2048,
          systemPrompt: '你是一个专业的客服助手，请友好、耐心地回答用户的问题。',
          isActive: true,
          createdAt: '2024-01-15T10:00:00Z',
          lastTrained: '2024-01-20T14:30:00Z',
          trainingStatus: 'completed' as const
        },
        {
          id: 'bot-2',
          name: '技术支持',
          description: '技术问题解答机器人，专注于技术支持',
          model: 'gpt-4',
          temperature: 0.3,
          maxTokens: 4096,
          systemPrompt: '你是一个技术支持专家，请提供准确的技术解决方案。',
          isActive: false,
          createdAt: '2024-01-10T09:00:00Z',
          trainingStatus: 'idle' as const
        }
      ];
      setBotConfigs(mockConfigs);
    } catch (error) {
      console.error('加载机器人配置失败:', error);
      toast({
        title: '加载失败',
        description: '无法加载机器人配置列表',
        variant: 'destructive'
      });
    }
  };

  // 保存机器人配置
  const saveBotConfig = async () => {
    try {
      if (!configForm.name.trim()) {
        toast({
          title: '验证失败',
          description: '请输入机器人名称',
          variant: 'destructive'
        });
        return;
      }

      const newConfig = {
        id: selectedBotConfig || `bot-${Date.now()}`,
        ...configForm,
        createdAt: selectedBotConfig ? 
          botConfigs.find(c => c.id === selectedBotConfig)?.createdAt || new Date().toISOString() :
          new Date().toISOString(),
        trainingStatus: 'idle' as const
      };

      if (selectedBotConfig) {
        // 更新现有配置
        setBotConfigs(prev => prev.map(config => 
          config.id === selectedBotConfig ? newConfig : config
        ));
        toast({
          title: '更新成功',
          description: '机器人配置已更新',
          variant: 'default'
        });
      } else {
        // 创建新配置
        setBotConfigs(prev => [...prev, newConfig]);
        toast({
          title: '创建成功',
          description: '新的机器人配置已创建',
          variant: 'default'
        });
      }

      setShowConfigDialog(false);
      setSelectedBotConfig(null);
      setConfigForm({
        name: '',
        description: '',
        model: 'gpt-3.5-turbo',
        temperature: 0.7,
        maxTokens: 2048,
        systemPrompt: '',
        isActive: true
      });
    } catch (error) {
      console.error('保存机器人配置失败:', error);
      toast({
        title: '保存失败',
        description: '无法保存机器人配置',
        variant: 'destructive'
      });
    }
  };

  // 删除机器人配置
  const deleteBotConfig = async (configId: string) => {
    try {
      setBotConfigs(prev => prev.filter(config => config.id !== configId));
      toast({
        title: '删除成功',
        description: '机器人配置已删除',
        variant: 'default'
      });
    } catch (error) {
      console.error('删除机器人配置失败:', error);
      toast({
        title: '删除失败',
        description: '无法删除机器人配置',
        variant: 'destructive'
      });
    }
  };

  // 开始训练机器人
  const startTraining = async () => {
    try {
      if (!selectedBotConfig || !trainingData.trim()) {
        toast({
          title: '验证失败',
          description: '请选择机器人配置并输入训练数据',
          variant: 'destructive'
        });
        return;
      }

      setTrainingStatus('training');
      setTrainingProgress(0);

      // 模拟训练进度
      const progressInterval = setInterval(() => {
        setTrainingProgress(prev => {
          if (prev >= 100) {
            clearInterval(progressInterval);
            setTrainingStatus('completed');
            setBotConfigs(prevConfigs => prevConfigs.map(config => 
              config.id === selectedBotConfig ? {
                ...config,
                lastTrained: new Date().toISOString(),
                trainingStatus: 'completed' as const
              } : config
            ));
            toast({
              title: '训练完成',
              description: '机器人训练已成功完成',
              variant: 'default'
            });
            return 100;
          }
          return prev + Math.random() * 10;
        });
      }, 500);

      setTimeout(() => {
        if (progressInterval) {
          clearInterval(progressInterval);
          setTrainingProgress(100);
          setTrainingStatus('completed');
        }
      }, 10000);

    } catch (error) {
      console.error('训练失败:', error);
      setTrainingStatus('error');
      toast({
        title: '训练失败',
        description: '机器人训练过程中出现错误',
        variant: 'destructive'
      });
    }
  };

  // 打开配置对话框
  const openConfigDialog = (configId?: string) => {
    if (configId) {
      const config = botConfigs.find(c => c.id === configId);
      if (config) {
        setSelectedBotConfig(configId);
        setConfigForm({
          name: config.name,
          description: config.description,
          model: config.model,
          temperature: config.temperature,
          maxTokens: config.maxTokens,
          systemPrompt: config.systemPrompt,
          isActive: config.isActive
        });
      }
    } else {
      setSelectedBotConfig(null);
      setConfigForm({
        name: '',
        description: '',
        model: 'gpt-3.5-turbo',
        temperature: 0.7,
        maxTokens: 2048,
        systemPrompt: '',
        isActive: true
      });
    }
    setShowConfigDialog(true);
  };

  // 打开训练对话框
  const openTrainingDialog = (configId: string) => {
    setSelectedBotConfig(configId);
    setTrainingData('');
    setTrainingStatus('idle');
    setTrainingProgress(0);
    setShowTrainingDialog(true);
  };

  // 切换机器人激活状态
  const toggleBotActive = async (configId: string) => {
    try {
      setBotConfigs(prev => prev.map(config => 
        config.id === configId ? { ...config, isActive: !config.isActive } : config
      ));
      const config = botConfigs.find(c => c.id === configId);
      toast({
        title: '状态更新',
        description: `机器人"${config?.name}"已${config?.isActive ? '停用' : '启用'}`,
        variant: 'default'
      });
    } catch (error) {
      console.error('切换机器人状态失败:', error);
      toast({
        title: '操作失败',
        description: '无法切换机器人状态',
        variant: 'destructive'
      });
    }
  };

  // 加载聊天数据统计
  const loadAnalyticsData = async () => {
    try {
      setAnalyticsLoading(true);
      // 模拟API调用
      const mockData = {
        totalSessions: sessions.length,
        totalMessages: sessions.reduce((sum, session) => sum + (session.message_count || 0), 0),
        avgSessionLength: 15.5,
        avgResponseTime: 2.3,
        userSatisfaction: 4.2,
        topTopics: [
          { topic: '技术支持', count: 45 },
          { topic: '产品咨询', count: 32 },
          { topic: '账户问题', count: 28 },
          { topic: '功能建议', count: 15 }
        ],
        dailyStats: [
          { date: '2024-01-15', sessions: 12, messages: 156 },
          { date: '2024-01-16', sessions: 18, messages: 234 },
          { date: '2024-01-17', sessions: 15, messages: 189 },
          { date: '2024-01-18', sessions: 22, messages: 287 },
          { date: '2024-01-19', sessions: 19, messages: 245 },
          { date: '2024-01-20', sessions: 25, messages: 321 },
          { date: '2024-01-21', sessions: 21, messages: 276 }
        ],
        weeklyStats: [],
        monthlyStats: []
      };
      setAnalyticsData(mockData);
    } catch (error) {
      console.error('加载统计数据失败:', error);
    } finally {
      setAnalyticsLoading(false);
    }
  };

  // 导出统计数据
  const exportAnalyticsData = async () => {
    try {
      const data = {
        ...analyticsData,
        exportTime: new Date().toISOString(),
        timeRange: analyticsTimeRange,
        dateRange: exportDateRange
      };

      let content = '';
      let filename = '';
      let mimeType = '';

      switch (exportFormat) {
        case 'csv':
          content = convertToCSV(data);
          filename = `chat-analytics-${new Date().toISOString().split('T')[0]}.csv`;
          mimeType = 'text/csv';
          break;
        case 'json':
          content = JSON.stringify(data, null, 2);
          filename = `chat-analytics-${new Date().toISOString().split('T')[0]}.json`;
          mimeType = 'application/json';
          break;
        case 'excel':
          // 简化的Excel导出（实际应使用专门的库）
          content = convertToCSV(data);
          filename = `chat-analytics-${new Date().toISOString().split('T')[0]}.xlsx`;
          mimeType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
          break;
      }

      const blob = new Blob([content], { type: mimeType });
      const url = URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      link.download = filename;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      URL.revokeObjectURL(url);

      setShowExportDialog(false);
      toast({
        title: '导出成功',
        description: `统计数据已导出为 ${exportFormat.toUpperCase()} 格式`,
        variant: 'default'
      });
    } catch (error) {
      console.error('导出统计数据失败:', error);
      toast({
        title: '导出失败',
        description: '无法导出统计数据',
        variant: 'destructive'
      });
    }
  };

  // 转换为CSV格式
  const convertToCSV = (data: any) => {
    const headers = ['指标', '数值'];
    const rows = [
      ['总会话数', data.totalSessions],
      ['总消息数', data.totalMessages],
      ['平均会话长度(分钟)', data.avgSessionLength],
      ['平均响应时间(秒)', data.avgResponseTime],
      ['用户满意度', data.userSatisfaction]
    ];

    const csvContent = [headers, ...rows]
      .map(row => row.map(cell => `"${cell}"`).join(','))
      .join('\n');

    return csvContent;
  };

  // 刷新统计数据
  const refreshAnalytics = () => {
    loadAnalyticsData();
  };

  // 加载审核日志
  const loadAuditLogs = async () => {
    setAuditLoading(true);
    try {
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 1000));
      
      const mockAuditLogs = [
        {
          id: 1,
          messageId: 'msg_001',
          content: '这是一条包含敏感词的消息',
          filteredWords: ['敏感词'],
          action: 'blocked',
          userId: 'user_123',
          sessionId: 'session_456',
          timestamp: new Date(Date.now() - 3600000).toISOString(),
          severity: 'high'
        },
        {
          id: 2,
          messageId: 'msg_002',
          content: '这是一条需要警告的消息',
          filteredWords: ['警告词'],
          action: 'warning',
          userId: 'user_789',
          sessionId: 'session_012',
          timestamp: new Date(Date.now() - 7200000).toISOString(),
          severity: 'medium'
        }
      ];
      
      setAuditLogs(mockAuditLogs);
      
      // 更新过滤统计
      setFilterStats({
        totalFiltered: 156,
        todayFiltered: 23,
        blockedMessages: 89,
        warningMessages: 67
      });
    } catch (error) {
      console.error('加载审核日志失败:', error);
    } finally {
      setAuditLoading(false);
    }
  };

  // 添加敏感词
  const addSensitiveWord = () => {
    if (!newSensitiveWord.trim()) return;
    
    if (sensitiveWords.includes(newSensitiveWord.trim())) {
      alert('该敏感词已存在');
      return;
    }
    
    setSensitiveWords([...sensitiveWords, newSensitiveWord.trim()]);
    setNewSensitiveWord('');
  };

  // 删除敏感词
  const removeSensitiveWord = (word: string) => {
    setSensitiveWords(sensitiveWords.filter(w => w !== word));
  };

  // 更新过滤规则
  const updateFilterRules = (rules: any) => {
    setFilterRules({ ...filterRules, ...rules });
  };

  // 检测消息中的敏感词
  const detectSensitiveWords = (content: string) => {
    const foundWords = sensitiveWords.filter(word => 
      content.toLowerCase().includes(word.toLowerCase())
    );
    return foundWords;
  };

  // 处理内容审核
  const handleContentAudit = async (messageId: string, action: 'approve' | 'reject') => {
    try {
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 500));
      
      // 更新审核日志
      setAuditLogs(logs => 
        logs.map(log => 
          log.messageId === messageId 
            ? { ...log, action: action === 'approve' ? 'approved' : 'rejected' }
            : log
        )
      );
      
      console.log(`消息 ${messageId} 已${action === 'approve' ? '通过' : '拒绝'}审核`);
    } catch (error) {
      console.error('处理审核失败:', error);
    }
  };

  // 导出审核日志
  const exportAuditLogs = () => {
    const csvContent = [
      ['ID', '消息ID', '内容', '敏感词', '处理动作', '用户ID', '会话ID', '时间', '严重程度'].join(','),
      ...auditLogs.map(log => [
        log.id,
        log.messageId,
        `"${log.content}"`,
        `"${log.filteredWords.join(', ')}"`,
        log.action,
        log.userId,
        log.sessionId,
        log.timestamp,
        log.severity
      ].join(','))
    ].join('\n');
    
    const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
    const link = document.createElement('a');
    link.href = URL.createObjectURL(blob);
    link.download = `audit-logs-${new Date().toISOString().split('T')[0]}.csv`;
    link.click();
  };

  // 刷新审核数据
  const refreshAuditData = () => {
    loadAuditLogs();
  };

  // 导出聊天记录
  const handleExportChat = () => {
    if (!selectedSession || messages.length === 0) {
      alert('没有可导出的聊天记录');
      return;
    }

    const chatData = {
      session: selectedSession,
      messages: messages,
      exportTime: new Date().toISOString()
    };

    const dataStr = JSON.stringify(chatData, null, 2);
    const dataBlob = new Blob([dataStr], { type: 'application/json' });
    const url = URL.createObjectURL(dataBlob);
    
    const link = document.createElement('a');
    link.href = url;
    link.download = `chat-${selectedSession.session_id}-${new Date().toISOString().split('T')[0]}.json`;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    URL.revokeObjectURL(url);
  };

  // 流式发送消息
  const handleSendMessageStream = async () => {
    if (!newMessage.trim() || !selectedSession || isStreaming) return;

    // 检查错误信息是否已填写
    if (!errorInfo.trim()) {
      alert('请先填写错误信息，不能为空！');
      return;
    }

    try {
      setSendingMessage(true);
      setIsStreaming(true);
      setStreamingSessionId(selectedSession.session_id);
      setConnectionStatus('connecting');
      
      const userMessageContent = newMessage;
      setNewMessage('');
      // 发送消息后不清空错误信息，保持用户输入的错误信息
      
      const tempUserMessage: ApiChatMessage = {
        id: Date.now(),
        message_id: `temp-${Date.now()}`,
        session_id: selectedSession.id,
        role: 'user',
        content: userMessageContent,
        created_at: new Date().toISOString()
      };
      
      // 添加临时用户消息到当前消息列表
      const updatedMessages = [...messages, tempUserMessage];
      setMessages(updatedMessages);
      
      setAiThinking(true);
      let seconds = 0;
      const timer = setInterval(() => {
        seconds += 1;
        setAiThinkingTime(seconds);
      }, 1000);
      setAiThinkingTimer(timer);
      
      const token = localStorage.getItem('access_token');
      // 直接使用API_BASE_URL常量
      const baseURL = 'http://localhost:8000';
      const streamUrl = `${baseURL}/api/v1/chat/sessions/${selectedSession.session_id}/messages/stream`;
      
      setStreamingMessage('');

      const response = await fetch(streamUrl, {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json',
          'Accept': 'text/event-stream',
        },
        body: JSON.stringify({
          content: userMessageContent,
          content_type: 'text',
          inputs: {
            errorinfo: errorInfo // 添加errorinfo字段
          }
        })
      });
      
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }
      
      setConnectionStatus('connected');
      
      const reader = response.body?.getReader();
      const decoder = new TextDecoder();
      let buffer = '';
      let currentAiMessage = '';
      
      if (reader) {
        try {
          while (true) {
            const { done, value } = await reader.read();
            
            if (done) break;
            
            buffer += decoder.decode(value, { stream: true });
            const lines = buffer.split('\n');
            buffer = lines.pop() || '';
            
            for (const line of lines) {
              if (line.trim() === '') continue;
              
              if (line.startsWith('data: ')) {
                const dataStr = line.slice(6);
                
                if (dataStr === '[DONE]') {
                  console.log('流式响应完成');
                  break;
                }
                
                try {
                  const data = JSON.parse(dataStr);
                  const eventType = data.event;
                  
                  console.log('接收到流式事件:', eventType, data);
                  
                  switch (eventType) {
                    case 'start':
                      console.log('流式响应开始');
                      break;
                      
                    case 'message':
                      if (data.data && data.data.answer) {
                        currentAiMessage += data.data.answer;
                        // 显示流式消息
                        setStreamingMessage(currentAiMessage);
                        // 设置消息正在接收状态
                        setMessageSaveStatus('none');
                      }
                      break;
                      
                    case 'message_end':
                      if (data.data) {
                        // 消息结束时，设置保存状态为正在保存
                        console.log('流式消息结束，正在保存到数据库...');
                        setMessageSaveStatus('saving');
                        // 保持流式消息显示，直到收到saved事件
                        // 确保流式消息内容完整
                        if (data.data.answer && data.data.answer !== currentAiMessage) {
                          currentAiMessage = data.data.answer;
                          setStreamingMessage(currentAiMessage);
                        }
                      }
                      break;
                      
                    case 'saved':
                      console.log('消息已保存到数据库');
                      setMessageSaveStatus('saved');
                      // 消息保存后重新加载最新数据，确保数据一致性
                      if (selectedSession && data.data?.ai_message) {
                        // 先重新加载消息列表，然后再清空流式消息
                        loadMessages(selectedSession.session_id).then(() => {
                          // 消息加载完成后再清空流式消息和重置状态
                          setStreamingMessage('');
                          setMessageSaveStatus('none');
                        }).catch(() => {
                          // 如果加载失败，也要清空流式消息
                          setStreamingMessage('');
                          setMessageSaveStatus('failed');
                          setTimeout(() => setMessageSaveStatus('none'), 3000);
                        });
                      }
                      break;
                      
                    case 'save_error':
                      console.error('消息保存失败:', data.data);
                      setMessageSaveStatus('failed');
                      // 显示保存失败的提示
                      const saveErrorMessage: ApiChatMessage = {
                        id: Date.now(),
                        message_id: `save-error-${Date.now()}`,
                        session_id: selectedSession.id,
                        role: 'assistant',
                        content: `消息保存失败: ${data.data.message || '未知错误'}`,
                        created_at: new Date().toISOString()
                      };
                      const updatedMessagesWithError = [...messages, saveErrorMessage];
                      setMessages(updatedMessagesWithError);
                      setStreamingMessage('');
                      // 3秒后重置保存状态
                      setTimeout(() => setMessageSaveStatus('none'), 3000);
                      break;
                      
                    case 'error_saved':
                      console.log('错误消息已保存到数据库');
                      // 错误消息保存后也重新加载数据
                      if (selectedSession) {
                        loadMessages(selectedSession.session_id).then(() => {
                          setStreamingMessage('');
                          setMessageSaveStatus('none');
                        }).catch(() => {
                          setStreamingMessage('');
                          setMessageSaveStatus('failed');
                          setTimeout(() => setMessageSaveStatus('none'), 3000);
                        });
                      }
                      break;
                      
                    case 'error':
                      console.error('流式响应错误:', data.data);
                      const errorMessage: ApiChatMessage = {
                        id: Date.now(),
                        message_id: `error-${Date.now()}`,
                        session_id: selectedSession.id,
                        role: 'assistant',
                        content: `抱歉，AI服务暂时不可用：${data.data.message || '未知错误'}`,
                        created_at: new Date().toISOString()
                      };
                      // 更新消息列表
                      const updatedMessages = [...messages, errorMessage];
                      setMessages(updatedMessages);
                      setStreamingMessage('');
                      break;
                      
                    case 'complete':
                      console.log('流式响应完全完成');
                      break;
                      
                    case 'heartbeat':
                      console.log('收到心跳信号');
                      break;
                      
                    default:
                      console.log('未知事件类型:', eventType, data);
                  }
                } catch (parseError) {
                  console.warn('解析流式数据失败:', parseError, dataStr);
                }
              }
            }
          }
        } catch (streamError) {
          console.error('流式读取错误:', streamError);
          setConnectionStatus('error');
        } finally {
          reader.releaseLock();
        }
      }
      
      loadSessions();
      
    } catch (error) {
      console.error('流式发送消息失败:', error);
      setConnectionStatus('error');
      

      
      const errorMessage: ApiChatMessage = {
        id: Date.now(),
        message_id: `error-${Date.now()}`,
        session_id: selectedSession.id,
        role: 'assistant',
        content: `发送消息失败: ${error instanceof Error ? error.message : '未知错误'}`,
        created_at: new Date().toISOString()
      };
      // 更新消息列表
      const updatedMessages = [...messages, errorMessage];
      setMessages(updatedMessages);
      
      toast({
        title: '发送失败',
        description: '无法发送消息，请稍后重试',
        variant: 'destructive'
      });
    } finally {
      setSendingMessage(false);
      setIsStreaming(false);
      setStreamingSessionId(null);
      setAiThinking(false);
      setAiThinkingTime(0);
      setStreamingMessage('');
      setConnectionStatus('disconnected');
      
      if (aiThinkingTimer) {
        clearInterval(aiThinkingTimer);
        setAiThinkingTimer(null);
      }
    }
  };

  const handleSendMessage = async () => {
    return handleSendMessageStream();
  };

  const getStatusBadge = (status: string) => {
    const statusConfig = {
      active: { label: '进行中', className: 'bg-green-100 text-green-800' },
      pending: { label: '待处理', className: 'bg-yellow-100 text-yellow-800' },
      resolved: { label: '已解决', className: 'bg-blue-100 text-blue-800' },
      closed: { label: '已关闭', className: 'bg-gray-100 text-gray-800' }
    };
    const config = statusConfig[status as keyof typeof statusConfig] || statusConfig.active;
    return (
      <Badge className={config.className}>
        {config.label}
      </Badge>
    );
  };

  const formatTime = (dateString: string) => {
    const date = new Date(dateString);
    const now = new Date();
    const diff = now.getTime() - date.getTime();
    const minutes = Math.floor(diff / 60000);
    const hours = Math.floor(diff / 3600000);
    const days = Math.floor(diff / 86400000);

    if (minutes < 1) return '刚刚';
    if (minutes < 60) return `${minutes}分钟前`;
    if (hours < 24) return `${hours}小时前`;
    if (days < 7) return `${days}天前`;
    return date.toLocaleDateString();
  };

  // 使用状态来存储过滤后的会话，支持异步消息内容搜索
  const [filteredSessions, setFilteredSessions] = useState<ApiChatSession[]>([]);
  
  // 过滤会话的函数
  const filterSessions = async () => {
    let filtered = sessions.filter(session => {
      // 基础搜索和状态过滤
      const matchesSearch = session.title.toLowerCase().includes(searchTerm.toLowerCase());
      const matchesStatus = statusFilter === 'all' || session.status === statusFilter;
      const matchesArchived = showArchived ? session.status === 'archived' : session.status !== 'archived';
      
      // 时间范围过滤
      let matchesDateRange = true;
      if (dateRange !== 'all') {
        const sessionDate = new Date(session.created_at);
        const now = new Date();
        const daysDiff = Math.floor((now.getTime() - sessionDate.getTime()) / (1000 * 60 * 60 * 24));
        
        switch (dateRange) {
          case 'today':
            matchesDateRange = daysDiff === 0;
            break;
          case 'week':
            matchesDateRange = daysDiff <= 7;
            break;
          case 'month':
            matchesDateRange = daysDiff <= 30;
            break;
          case 'quarter':
            matchesDateRange = daysDiff <= 90;
            break;
        }
      }
      
      // 消息数量过滤
      let matchesMessageCount = true;
      if (messageCountFilter !== 'all') {
        const messageCount = session.message_count || 0;
        switch (messageCountFilter) {
          case 'empty':
            matchesMessageCount = messageCount === 0;
            break;
          case 'few':
            matchesMessageCount = messageCount > 0 && messageCount <= 5;
            break;
          case 'moderate':
            matchesMessageCount = messageCount > 5 && messageCount <= 20;
            break;
          case 'many':
            matchesMessageCount = messageCount > 20;
            break;
        }
      }
      
      return matchesSearch && matchesStatus && matchesArchived && matchesDateRange && matchesMessageCount;
    });
    
    // 如果有消息内容搜索，进行异步过滤
    if (contentSearch.trim()) {
      const contentFilteredSessions = [];
      for (const session of filtered) {
        const hasMatchingContent = await searchInMessages(session.session_id, contentSearch);
        if (hasMatchingContent) {
          contentFilteredSessions.push(session);
        }
      }
      filtered = contentFilteredSessions;
    }
    
    setFilteredSessions(filtered);
  };

  useEffect(() => {
    // 设置全局token过期处理器
    setGlobalTokenExpiryHandler(handleTokenExpiry);
    
    loadSessions();
    loadOnlineUsers();
    loadBotConfigs();
    loadAnalyticsData();
    loadAuditLogs();
  }, [handleTokenExpiry]);
  
  // 定期更新在线用户状态
  useEffect(() => {
    const interval = setInterval(() => {
      loadOnlineUsers();
    }, 30000); // 每30秒更新一次
    
    return () => clearInterval(interval);
  }, []);

  useEffect(() => {
    if (selectedSession) {
      loadMessages(selectedSession.session_id);
    }
  }, [selectedSession]);
  
  // 当过滤条件或会话数据变化时，重新过滤会话
  useEffect(() => {
    filterSessions();
  }, [sessions, searchTerm, statusFilter, showArchived, dateRange, messageCountFilter, contentSearch]);

  useEffect(() => {
    return () => {
      // 清理计时器
      if (aiThinkingTimer) {
        clearInterval(aiThinkingTimer);
      }
    };
  }, []);

  return (
    <div className="min-h-screen bg-gray-50 p-6">
      <div className="max-w-7xl mx-auto">
        <div className="flex items-center justify-between mb-6">
          <div>
            <h1 className="text-3xl font-bold text-gray-900">智能聊天管理</h1>
            <p className="text-gray-600 mt-1">管理客户对话和AI智能回复 | 支持流式响应</p>
          </div>
          <div className="flex space-x-3">
            <Button 
              variant={showArchived ? "default" : "outline"} 
              size="sm" 
              onClick={() => setShowArchived(!showArchived)}
            >
              {showArchived ? <ArchiveRestore className="w-4 h-4 mr-2" /> : <Archive className="w-4 h-4 mr-2" />}
              {showArchived ? '显示活跃' : '显示归档'}
            </Button>
            <Button 
              variant={showBulkActions ? "default" : "outline"} 
              size="sm" 
              onClick={() => {
                setShowBulkActions(!showBulkActions);
                setSelectedSessions([]);
              }}
            >
              <CheckSquare className="w-4 h-4 mr-2" />
              批量操作
            </Button>
            <Button variant="outline" size="sm" onClick={loadSessions}>
              <RefreshCw className="w-4 h-4 mr-2" />
              刷新
            </Button>
            <Button 
              variant={showUserMonitor ? "default" : "outline"} 
              size="sm" 
              onClick={() => setShowUserMonitor(!showUserMonitor)}
            >
              <Users className="w-4 h-4 mr-2" />
              用户监控
            </Button>
            <Button 
              variant={showBotConfig ? "default" : "outline"} 
              size="sm" 
              onClick={() => setShowBotConfig(!showBotConfig)}
            >
              <Bot className="w-4 h-4 mr-2" />
              机器人配置
            </Button>
            <Button 
              variant={showAnalytics ? "default" : "outline"} 
              size="sm" 
              onClick={() => setShowAnalytics(!showAnalytics)}
            >
              <BarChart3 className="w-4 h-4 mr-2" />
              数据统计
            </Button>
            <Button 
              variant={showContentFilter ? "default" : "outline"} 
              size="sm" 
              onClick={() => setShowContentFilter(!showContentFilter)}
            >
              <Eye className="w-4 h-4 mr-2" />
              内容审核
            </Button>
            <Dialog open={showNewSessionDialog} onOpenChange={setShowNewSessionDialog}>
              <DialogTrigger asChild>
                <Button size="sm">
                  <Plus className="w-4 h-4 mr-2" />
                  新建对话
                </Button>
              </DialogTrigger>
              <DialogContent>
                <DialogHeader>
                  <DialogTitle>创建新对话</DialogTitle>
                  <DialogDescription>
                    请输入对话标题来创建一个新的聊天会话
                  </DialogDescription>
                </DialogHeader>
                <div className="grid gap-4 py-4">
                  <div className="grid grid-cols-4 items-center gap-4">
                    <Label htmlFor="title" className="text-right">
                      标题
                    </Label>
                    <Input
                      id="title"
                      value={newSessionTitle}
                      onChange={(e) => setNewSessionTitle(e.target.value)}
                      className="col-span-3"
                      placeholder="请输入对话标题"
                    />
                  </div>
                </div>
                <DialogFooter>
                  <Button
                    onClick={handleCreateSession}
                    disabled={creatingSession || !newSessionTitle.trim()}
                  >
                    {creatingSession && <Loader2 className="w-4 h-4 mr-2 animate-spin" />}
                    创建
                  </Button>
                </DialogFooter>
              </DialogContent>
            </Dialog>
          </div>
        </div>

        <div className="grid grid-cols-1 lg:grid-cols-4 gap-6">
          <div className="lg:col-span-1">
            <Card className="h-[calc(100vh-200px)]">
              <CardHeader className="pb-3">
                <div className="flex items-center justify-between">
                  <CardTitle className="text-lg">
                    {showArchived ? '归档对话' : '对话列表'}
                  </CardTitle>
                  <span className="text-sm text-gray-500">
                    {filteredSessions.length} / {sessions.length} 个对话
                  </span>
                </div>
                
                {showBulkActions && (
                  <div className="flex items-center justify-between p-2 bg-blue-50 rounded-md">
                    <div className="flex items-center space-x-2">
                      <Button
                        variant="ghost"
                        size="sm"
                        onClick={handleSelectAll}
                        className="h-8"
                      >
                        {selectedSessions.length === filteredSessions.length && filteredSessions.length > 0 ? (
                          <CheckSquare className="w-4 h-4" />
                        ) : (
                          <Square className="w-4 h-4" />
                        )}

       {/* 内容审核面板 */}
       {showContentFilter && (
         <Card className="mt-6">
           <CardHeader>
             <div className="flex items-center justify-between">
               <CardTitle className="text-lg flex items-center">
                 <Eye className="w-5 h-5 mr-2" />
                 内容审核与过滤
               </CardTitle>
               <div className="flex items-center space-x-2">
                 <Button
                   variant="outline"
                   size="sm"
                   onClick={refreshAuditData}
                   disabled={auditLoading}
                 >
                   {auditLoading ? (
                     <Loader2 className="w-4 h-4 animate-spin" />
                   ) : (
                     <RefreshCw className="w-4 h-4" />
                   )}
                 </Button>
                 <Button
                   variant="outline"
                   size="sm"
                   onClick={() => setShowAuditDialog(true)}
                 >
                   <Download className="w-4 h-4 mr-2" />
                   导出日志
                 </Button>
               </div>
             </div>
           </CardHeader>
           <CardContent>
             {auditLoading ? (
               <div className="flex items-center justify-center py-8">
                 <Loader2 className="w-6 h-6 animate-spin mr-2" />
                 <span>加载审核数据中...</span>
               </div>
             ) : (
               <div className="space-y-6">
                 {/* 过滤统计概览 */}
                 <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
                   <div className="bg-red-50 p-4 rounded-lg border border-red-200">
                     <div className="flex items-center justify-between">
                       <div>
                         <p className="text-sm text-red-600 font-medium">拦截消息</p>
                         <p className="text-2xl font-bold text-red-700">{filterStats.blockedMessages}</p>
                       </div>
                       <Shield className="w-8 h-8 text-red-500" />
                     </div>
                   </div>
                   
                   <div className="bg-yellow-50 p-4 rounded-lg border border-yellow-200">
                     <div className="flex items-center justify-between">
                       <div>
                         <p className="text-sm text-yellow-600 font-medium">敏感词数量</p>
                         <p className="text-2xl font-bold text-yellow-700">{sensitiveWords.length}</p>
                       </div>
                       <AlertTriangle className="w-8 h-8 text-yellow-500" />
                     </div>
                   </div>
                   
                   <div className="bg-blue-50 p-4 rounded-lg border border-blue-200">
                     <div className="flex items-center justify-between">
                       <div>
                         <p className="text-sm text-blue-600 font-medium">审核规则</p>
                         <p className="text-2xl font-bold text-blue-700">{Object.keys(filterRules).length}</p>
                       </div>
                       <Settings className="w-8 h-8 text-blue-500" />
                     </div>
                   </div>
                   
                   <div className="bg-green-50 p-4 rounded-lg border border-green-200">
                     <div className="flex items-center justify-between">
                       <div>
                         <p className="text-sm text-green-600 font-medium">通过率</p>
                         <p className="text-2xl font-bold text-green-700">{filterStats.passRate}%</p>
                       </div>
                       <CheckCircle className="w-8 h-8 text-green-500" />
                     </div>
                   </div>
                 </div>

                 {/* 敏感词管理 */}
                 <div className="space-y-4">
                   <div className="flex items-center justify-between">
                     <h3 className="text-lg font-semibold">敏感词管理</h3>
                     <div className="flex items-center space-x-2">
                       <Input
                         placeholder="添加敏感词"
                         value={newSensitiveWord}
                         onChange={(e) => setNewSensitiveWord(e.target.value)}
                         className="w-48"
                         onKeyPress={(e) => {
                           if (e.key === 'Enter' && newSensitiveWord.trim()) {
                             addSensitiveWord();
                           }
                         }}
                       />
                       <Button
                         size="sm"
                         onClick={addSensitiveWord}
                         disabled={!newSensitiveWord.trim()}
                       >
                         <Plus className="w-4 h-4 mr-2" />
                         添加
                       </Button>
                     </div>
                   </div>
                   
                   <div className="border rounded-lg p-4 max-h-48 overflow-y-auto">
                     {sensitiveWords.length === 0 ? (
                       <p className="text-gray-500 text-center py-4">暂无敏感词</p>
                     ) : (
                       <div className="flex flex-wrap gap-2">
                         {sensitiveWords.map((word, index) => (
                           <div
                             key={index}
                             className="flex items-center bg-red-100 text-red-800 px-3 py-1 rounded-full text-sm"
                           >
                             <span>{word}</span>
                             <button
                               onClick={() => removeSensitiveWord(word)}
                               className="ml-2 text-red-600 hover:text-red-800"
                             >
                               <X className="w-3 h-3" />
                             </button>
                           </div>
                         ))}
                       </div>
                     )}
                   </div>
                 </div>

                 {/* 过滤规则配置 */}
                 <div className="space-y-4">
                   <h3 className="text-lg font-semibold">过滤规则配置</h3>
                   <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                     <div className="border rounded-lg p-4">
                       <div className="flex items-center justify-between mb-2">
                         <h4 className="font-medium">基础过滤</h4>
                         <div className="flex items-center space-x-2">
                           <Switch
                             checked={filterRules.enabled}
                             onCheckedChange={(checked) => {
                               setFilterRules(prev => ({ ...prev, enabled: checked }));
                             }}
                           />
                           <span className={`text-sm ${
                             filterRules.enabled ? 'text-green-600' : 'text-gray-400'
                           }`}>
                             {filterRules.enabled ? '启用' : '禁用'}
                           </span>
                         </div>
                       </div>
                       <p className="text-sm text-gray-600 mb-2">基础敏感词过滤功能</p>
                     </div>
                     
                     <div className="border rounded-lg p-4">
                       <div className="flex items-center justify-between mb-2">
                         <h4 className="font-medium">严格模式</h4>
                         <div className="flex items-center space-x-2">
                           <Switch
                             checked={filterRules.strictMode}
                             onCheckedChange={(checked) => {
                               setFilterRules(prev => ({ ...prev, strictMode: checked }));
                             }}
                           />
                           <span className={`text-sm ${
                             filterRules.strictMode ? 'text-green-600' : 'text-gray-400'
                           }`}>
                             {filterRules.strictMode ? '启用' : '禁用'}
                           </span>
                         </div>
                       </div>
                       <p className="text-sm text-gray-600 mb-2">更严格的内容审核标准</p>
                     </div>
                     
                     <div className="border rounded-lg p-4">
                       <div className="flex items-center justify-between mb-2">
                         <h4 className="font-medium">自动拦截</h4>
                         <div className="flex items-center space-x-2">
                           <Switch
                             checked={filterRules.autoBlock}
                             onCheckedChange={(checked) => {
                               setFilterRules(prev => ({ ...prev, autoBlock: checked }));
                             }}
                           />
                           <span className={`text-sm ${
                             filterRules.autoBlock ? 'text-green-600' : 'text-gray-400'
                           }`}>
                             {filterRules.autoBlock ? '启用' : '禁用'}
                           </span>
                         </div>
                       </div>
                       <p className="text-sm text-gray-600 mb-2">自动拦截违规内容</p>
                     </div>
                     
                     <div className="border rounded-lg p-4">
                       <div className="flex items-center justify-between mb-2">
                         <h4 className="font-medium">管理员通知</h4>
                         <div className="flex items-center space-x-2">
                           <Switch
                             checked={filterRules.notifyAdmin}
                             onCheckedChange={(checked) => {
                               setFilterRules(prev => ({ ...prev, notifyAdmin: checked }));
                             }}
                           />
                           <span className={`text-sm ${
                             filterRules.notifyAdmin ? 'text-green-600' : 'text-gray-400'
                           }`}>
                             {filterRules.notifyAdmin ? '启用' : '禁用'}
                           </span>
                         </div>
                       </div>
                       <p className="text-sm text-gray-600 mb-2">违规时通知管理员</p>
                     </div>
                   </div>
                 </div>

                 {/* 审核日志 */}
                 <div className="space-y-4">
                   <h3 className="text-lg font-semibold">最近审核日志</h3>
                   <div className="border rounded-lg overflow-hidden">
                     <table className="w-full">
                       <thead className="bg-gray-50">
                         <tr>
                           <th className="px-4 py-3 text-left text-sm font-medium text-gray-700">时间</th>
                           <th className="px-4 py-3 text-left text-sm font-medium text-gray-700">用户</th>
                           <th className="px-4 py-3 text-left text-sm font-medium text-gray-700">内容</th>
                           <th className="px-4 py-3 text-left text-sm font-medium text-gray-700">规则</th>
                           <th className="px-4 py-3 text-left text-sm font-medium text-gray-700">结果</th>
                         </tr>
                       </thead>
                       <tbody className="divide-y divide-gray-200">
                         {auditLogs.slice(0, 10).map((log, index) => (
                           <tr key={index}>
                             <td className="px-4 py-3 text-sm text-gray-900">
                               {new Date(log.timestamp).toLocaleString()}
                             </td>
                             <td className="px-4 py-3 text-sm text-gray-900">{log.userId}</td>
                             <td className="px-4 py-3 text-sm text-gray-900 max-w-xs truncate">
                               {log.content}
                             </td>
                             <td className="px-4 py-3 text-sm text-gray-900">{log.rule}</td>
                             <td className="px-4 py-3 text-sm">
                               <span className={`inline-flex items-center px-2 py-1 rounded-full text-xs font-medium ${
                                 log.action === 'blocked'
                                   ? 'bg-red-100 text-red-800'
                                   : log.action === 'warned'
                                   ? 'bg-yellow-100 text-yellow-800'
                                   : 'bg-green-100 text-green-800'
                               }`}>
                                 {log.action === 'blocked' ? '拦截' : log.action === 'warned' ? '警告' : '通过'}
                               </span>
                             </td>
                           </tr>
                         ))}
                       </tbody>
                     </table>
                   </div>
                   
                   {auditLogs.length > 10 && (
                     <div className="text-center">
                       <Button variant="outline" size="sm">
                         查看更多日志
                       </Button>
                     </div>
                   )}
                 </div>
               </div>
             )}
           </CardContent>
         </Card>
       )}
                      </Button>
                      <span className="text-sm text-gray-600">
                        已选择 {selectedSessions.length} 个对话
                      </span>
                    </div>
                    {selectedSessions.length > 0 && (
                      <div className="flex space-x-1">
                        <Button
                          variant="ghost"
                          size="sm"
                          onClick={handleBulkArchive}
                          disabled={bulkActionLoading}
                          className="h-8"
                        >
                          {bulkActionLoading ? (
                            <Loader2 className="w-4 h-4 animate-spin" />
                          ) : (
                            <Archive className="w-4 h-4" />
                          )}
                        </Button>
                        <Button
                          variant="ghost"
                          size="sm"
                          onClick={handleBulkDelete}
                          disabled={bulkActionLoading}
                          className="h-8 text-red-600 hover:text-red-700"
                        >
                          {bulkActionLoading ? (
                            <Loader2 className="w-4 h-4 animate-spin" />
                          ) : (
                            <Trash2 className="w-4 h-4" />
                          )}
                        </Button>
                      </div>
                    )}
                  </div>
                )}
                
                <div className="space-y-2">
                  <div className="relative">
                    <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4" />
                    <Input
                      placeholder="搜索对话标题..."
                      className="pl-10"
                      value={searchTerm}
                      onChange={(e) => setSearchTerm(e.target.value)}
                    />
                  </div>
                  
                  <div className="relative">
                    <MessageSquare className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4" />
                    <Input
                      placeholder="搜索消息内容..."
                      className="pl-10"
                      value={contentSearch}
                      onChange={(e) => setContentSearch(e.target.value)}
                    />
                  </div>
                  
                  <Select value={statusFilter} onValueChange={setStatusFilter}>
                    <SelectTrigger>
                      <SelectValue placeholder="筛选状态" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="all">全部状态</SelectItem>
                      <SelectItem value="active">进行中</SelectItem>
                      <SelectItem value="pending">待处理</SelectItem>
                      <SelectItem value="resolved">已解决</SelectItem>
                      <SelectItem value="closed">已关闭</SelectItem>
                      <SelectItem value="archived">已归档</SelectItem>
                    </SelectContent>
                  </Select>
                  
                  <div className="flex items-center justify-between">
                    <Button
                      variant="ghost"
                      size="sm"
                      onClick={() => setShowAdvancedFilters(!showAdvancedFilters)}
                      className="text-xs"
                    >
                      <Filter className="w-3 h-3 mr-1" />
                      {showAdvancedFilters ? '隐藏' : '显示'}高级过滤
                    </Button>
                    {(searchTerm || contentSearch || statusFilter !== 'all' || dateRange !== 'all' || messageCountFilter !== 'all') && (
                      <Button
                        variant="ghost"
                        size="sm"
                        onClick={clearAllFilters}
                        className="text-xs text-red-600 hover:text-red-700"
                      >
                        <X className="w-3 h-3 mr-1" />
                        清空
                      </Button>
                    )}
                  </div>
                  
                  {showAdvancedFilters && (
                    <div className="space-y-2 p-3 bg-gray-50 rounded-md">
                      <div>
                        <Label className="text-xs text-gray-600 mb-1 block">时间范围</Label>
                        <Select value={dateRange} onValueChange={setDateRange}>
                          <SelectTrigger className="h-8">
                            <SelectValue placeholder="选择时间范围" />
                          </SelectTrigger>
                          <SelectContent>
                            <SelectItem value="all">全部时间</SelectItem>
                            <SelectItem value="today">今天</SelectItem>
                            <SelectItem value="week">最近一周</SelectItem>
                            <SelectItem value="month">最近一月</SelectItem>
                            <SelectItem value="quarter">最近三月</SelectItem>
                          </SelectContent>
                        </Select>
                      </div>
                      
                      <div>
                        <Label className="text-xs text-gray-600 mb-1 block">消息数量</Label>
                        <Select value={messageCountFilter} onValueChange={setMessageCountFilter}>
                          <SelectTrigger className="h-8">
                            <SelectValue placeholder="选择消息数量" />
                          </SelectTrigger>
                          <SelectContent>
                            <SelectItem value="all">全部</SelectItem>
                            <SelectItem value="empty">无消息</SelectItem>
                            <SelectItem value="few">1-5条</SelectItem>
                            <SelectItem value="moderate">6-20条</SelectItem>
                            <SelectItem value="many">20条以上</SelectItem>
                          </SelectContent>
                        </Select>
                      </div>
                    </div>
                  )}
                </div>
              </CardHeader>
              
              <CardContent className="p-0">
                {loading ? (
                  <div className="flex items-center justify-center p-8">
                    <Loader2 className="w-6 h-6 animate-spin" />
                    <span className="ml-2">加载中...</span>
                  </div>
                ) : filteredSessions.length === 0 ? (
                  <div className="text-center p-8 text-gray-500">
                    <MessageSquare className="w-12 h-12 mx-auto mb-4 text-gray-300" />
                    <p>暂无对话记录</p>
                    <p className="text-sm">点击"新建对话"开始</p>
                  </div>
                ) : (
                  <div className="space-y-1 max-h-[calc(100vh-350px)] overflow-y-auto">
                    {filteredSessions.map((session) => (
                      <div
                        key={session.id}
                        className={`p-3 border-l-2 transition-colors group ${
                          selectedSession?.id === session.id
                            ? 'bg-blue-50 border-blue-500'
                            : selectedSessions.includes(session.session_id)
                            ? 'bg-blue-25 border-blue-300'
                            : 'border-transparent hover:bg-gray-50'
                        }`}
                      >
                        <div className="flex items-start space-x-3">
                          {showBulkActions && (
                            <Button
                              variant="ghost"
                              size="sm"
                              onClick={(e) => {
                                e.stopPropagation();
                                handleSelectSession(session.session_id);
                              }}
                              className="h-8 w-8 p-0 mt-1"
                            >
                              {selectedSessions.includes(session.session_id) ? (
                                <CheckSquare className="w-4 h-4" />
                              ) : (
                                <Square className="w-4 h-4" />
                              )}
                            </Button>
                          )}
                          
                          <Avatar className="w-8 h-8">
                            <AvatarFallback>
                              <MessageSquare className="w-4 h-4" />
                            </AvatarFallback>
                          </Avatar>
                          
                          <div 
                            className="flex-1 min-w-0 cursor-pointer"
                            onClick={() => {
                              // 切换到新会话
                              setSelectedSession(session);
                              // 清空当前消息，避免显示之前会话的内容
                              setMessages([]);
                              // 加载新会话的消息
                              loadMessages(session.session_id);
                              
                              // 重置流式响应状态
                              setStreamingMessage('');
                              setIsStreaming(false);
                              setStreamingSessionId(null);
                              setAiThinking(false);
                              setMessageSaveStatus('none');
                              // 切换会话时重置错误信息
                              setErrorInfo('');
                              if (aiThinkingTimer) {
                                clearInterval(aiThinkingTimer);
                                setAiThinkingTimer(null);
                              }
                            }}
                          >
                            <div className="flex items-center justify-between mb-1">
                              <div className="flex items-center space-x-2">
                                {editingSession === session.session_id ? (
                                  <Input
                                    value={editTitle}
                                    onChange={(e) => setEditTitle(e.target.value)}
                                    onBlur={() => handleEditSession(session.session_id, editTitle)}
                                    onKeyDown={(e) => {
                                      if (e.key === 'Enter') {
                                        handleEditSession(session.session_id, editTitle);
                                      } else if (e.key === 'Escape') {
                                        setEditingSession(null);
                                        setEditTitle('');
                                      }
                                    }}
                                    className="h-6 text-sm font-medium"
                                    autoFocus
                                    onClick={(e) => e.stopPropagation()}
                                  />
                                ) : (
                                  <h4 className="text-sm font-medium text-gray-900 truncate">
                                    {session.title}
                                  </h4>
                                )}
                                {session.archived && (
                                  <Archive className="w-4 h-4 text-gray-400" />
                                )}
                              </div>
                              <div className="flex items-center space-x-1">
                                {getStatusBadge(session.status)}
                                <div className="opacity-0 group-hover:opacity-100 transition-opacity flex space-x-1">
                                  <Button
                                    variant="ghost"
                                    size="sm"
                                    className="p-1 h-6 w-6"
                                    onClick={(e) => {
                                      e.stopPropagation();
                                      setEditingSession(session.session_id);
                                      setEditTitle(session.title);
                                    }}
                                  >
                                    <Edit className="w-3 h-3 text-gray-500" />
                                  </Button>
                                  <Button
                                    variant="ghost"
                                    size="sm"
                                    className="p-1 h-6 w-6"
                                    onClick={(e) => {
                                      e.stopPropagation();
                                      openExportDialog(session.session_id);
                                    }}
                                  >
                                    <Download className="w-3 h-3 text-green-500" />
                                  </Button>
                                  <Button
                                    variant="ghost"
                                    size="sm"
                                    className="p-1 h-6 w-6"
                                    onClick={(e) => {
                                      e.stopPropagation();
                                      openAssignDialog(session.session_id);
                                    }}
                                    title="分配给用户"
                                  >
                                    <Users className="w-3 h-3 text-purple-500" />
                                  </Button>
                                  <Button
                                    variant="ghost"
                                    size="sm"
                                    className="p-1 h-6 w-6"
                                    onClick={(e) => {
                                      e.stopPropagation();
                                      handleArchiveSession(session.session_id);
                                    }}
                                  >
                                    {session.archived ? (
                                      <ArchiveRestore className="w-3 h-3 text-blue-500" />
                                    ) : (
                                      <Archive className="w-3 h-3 text-gray-500" />
                                    )}
                                  </Button>
                                  <Button
                                    variant="ghost"
                                    size="sm"
                                    className="p-1 h-6 w-6"
                                    onClick={(e) => {
                                      e.stopPropagation();
                                      handleDeleteSession(session.session_id);
                                    }}
                                  >
                                    <X className="w-3 h-3 text-red-500" />
                                  </Button>
                                </div>
                              </div>
                            </div>
                            <p className="text-xs text-gray-600 mb-1">
                              消息数: {session.message_count}
                            </p>
                            <div className="flex items-center justify-between mt-2">
                              <span className="text-xs text-gray-400">
                                {formatTime(session.last_message_at || session.updated_at)}
                              </span>
                            </div>
                          </div>
                        </div>
                      </div>
                    ))}
                  </div>
                )}
              </CardContent>
            </Card>
          </div>

          <div className="lg:col-span-2">
            <Card className="h-[calc(100vh-200px)] flex flex-col">
              {selectedSession ? (
                <>
                  <CardHeader className="border-b">
                    <div className="flex items-center justify-between">
                      <div className="flex items-center space-x-3">
                        <Avatar>
                          <AvatarFallback>
                            <MessageSquare className="w-4 h-4" />
                          </AvatarFallback>
                        </Avatar>
                        <div>
                          <h3 className="font-medium">{selectedSession.title}</h3>
                          <p className="text-sm text-gray-500">
                            会话ID: {selectedSession.session_id}
                          </p>
                        </div>
                      </div>
                      <div className="flex items-center space-x-2">
                        {getStatusBadge(selectedSession.status)}
                        {connectionStatus !== 'disconnected' && (
                          <div className="flex items-center space-x-1">
                            <div className={`w-2 h-2 rounded-full ${
                              connectionStatus === 'connected' ? 'bg-green-500' :
                              connectionStatus === 'connecting' ? 'bg-yellow-500' :
                              connectionStatus === 'error' ? 'bg-red-500' : 'bg-gray-500'
                            }`}></div>
                            <span className="text-xs text-gray-500">
                              {connectionStatus === 'connected' ? '流式连接' :
                               connectionStatus === 'connecting' ? '连接中' :
                               connectionStatus === 'error' ? '连接错误' : '未连接'}
                            </span>
                          </div>
                        )}
                      </div>
                    </div>
                  </CardHeader>

                  <CardContent className="flex-1 p-4 overflow-y-auto">
                    {messages.length === 0 ? (
                      <div className="flex items-center justify-center h-full text-gray-500">
                        <div className="text-center">
                          <Bot className="w-12 h-12 mx-auto mb-4 text-gray-300" />
                          <p>还没有消息</p>
                          <p className="text-sm">发送第一条消息开始对话</p>
                        </div>
                      </div>
                    ) : (
                      <div className="space-y-4">
                        {messages.map((message) => (
                          <div
                            key={message.id}
                            className={`flex ${message.role === 'user' ? 'justify-end' : 'justify-start'}`}
                          >
                            <div className={`flex items-start space-x-2 max-w-[80%] ${
                              message.role === 'user' ? 'flex-row-reverse space-x-reverse' : ''
                            }`}>
                              <div className={`w-8 h-8 rounded-full flex items-center justify-center ${
                                message.role === 'user' ? 'bg-blue-500' : 'bg-gray-500'
                              }`}>
                                {message.role === 'user' ? (
                                  <User className="w-4 h-4 text-white" />
                                ) : (
                                  <Bot className="w-4 h-4 text-white" />
                                )}
                              </div>
                              <div className={`rounded-lg px-4 py-2 ${
                                message.role === 'user'
                                  ? 'bg-blue-500 text-white'
                                  : 'bg-gray-100 text-gray-900'
                              }`}>
                                <p className="text-sm whitespace-pre-line">{message.content}</p>
                                <div className="flex items-center justify-between mt-1">
                                  <p className={`text-xs ${
                                    message.role === 'user' ? 'text-blue-100' : 'text-gray-500'
                                  }`}>
                                    {formatTime(message.created_at)}
                                  </p>
                                  
                                  {/* AI消息的评分和反馈功能 */}
                                  {message.role === 'assistant' && (
                                    <div className="flex items-center space-x-2">
                                      {/* 快速评分星星 */}
                                      <div className="flex items-center space-x-1">
                                        {[1, 2, 3, 4, 5].map((star) => (
                                          <button
                                            key={star}
                                            onClick={() => quickRate(message.id, star)}
                                            className={`w-3 h-3 transition-colors ${
                                              (messageRatings[message.id] || 0) >= star
                                                ? 'text-yellow-400 hover:text-yellow-500'
                                                : 'text-gray-300 hover:text-yellow-300'
                                            }`}
                                          >
                                            ★
                                          </button>
                                        ))}
                                      </div>
                                      
                                      {/* 详细反馈按钮 */}
                                      <Button
                                        variant="ghost"
                                        size="sm"
                                        className="p-1 h-5 w-5 text-gray-400 hover:text-gray-600"
                                        onClick={() => openFeedbackDialog(selectedSession.session_id, message.id)}
                                      >
                                        <MessageSquare className="w-3 h-3" />
                                      </Button>
                                    </div>
                                  )}
                                </div>
                              </div>
                            </div>
                          </div>
                        ))}
                        
                        {streamingMessage && streamingSessionId === selectedSession?.session_id && (
                          <div className="flex justify-start">
                            <div className="flex items-start space-x-2 max-w-[80%]">
                              <div className="w-8 h-8 rounded-full flex items-center justify-center bg-gray-500">
                                <Bot className="w-4 h-4 text-white" />
                              </div>
                              <div className="rounded-lg px-4 py-2 bg-gray-100 text-gray-900">
                                <p className="text-sm whitespace-pre-line">{streamingMessage}</p>
                                <div className="flex items-center space-x-2 mt-1">
                                  {messageSaveStatus === 'saving' ? (
                                    <>
                                      <Loader2 className="w-3 h-3 animate-spin text-blue-500" />
                                      <p className="text-xs text-blue-500">正在保存到数据库...</p>
                                    </>
                                  ) : messageSaveStatus === 'saved' ? (
                                    <>
                                      <div className="w-3 h-3 rounded-full bg-green-500"></div>
                                      <p className="text-xs text-green-500">已保存，正在刷新...</p>
                                    </>
                                  ) : messageSaveStatus === 'failed' ? (
                                    <>
                                      <div className="w-3 h-3 rounded-full bg-red-500"></div>
                                      <p className="text-xs text-red-500">保存失败</p>
                                    </>
                                  ) : (
                                    <>
                                      <Loader2 className="w-3 h-3 animate-spin text-gray-500" />
                                      <p className="text-xs text-gray-500">正在接收...</p>
                                    </>
                                  )}
                                </div>
                              </div>
                            </div>
                          </div>
                        )}
                        
                        {aiThinking && !streamingMessage && (
                          <div className="flex justify-start">
                            <div className="flex items-start space-x-2 max-w-[80%]">
                              <div className="w-8 h-8 rounded-full flex items-center justify-center bg-gray-500">
                                <Bot className="w-4 h-4 text-white" />
                              </div>
                              <div className="rounded-lg px-4 py-2 bg-gray-100 text-gray-900">
                                <div className="flex items-center space-x-2">
                                  <Loader2 className="w-4 h-4 animate-spin text-gray-500" />
                                  <p className="text-sm">
                                    {connectionStatus === 'connecting' ? '正在连接...' : 
                                     connectionStatus === 'connected' ? '等待AI响应...' : 
                                     'AI正在思考中...'}
                                  </p>
                                </div>
                                <p className="text-xs mt-1 text-gray-500">
                                  已用时 {aiThinkingTime} 秒
                                  {aiThinkingTime > 30 && " (可能需要较长时间)"}
                                  {aiThinkingTime > 120 && " (正在处理复杂问题，请耐心等待)"}
                                </p>
                                {connectionStatus !== 'disconnected' && (
                                  <div className="flex items-center space-x-1 mt-1">
                                    <div className={`w-2 h-2 rounded-full ${
                                      connectionStatus === 'connected' ? 'bg-green-500' :
                                      connectionStatus === 'connecting' ? 'bg-yellow-500' :
                                      connectionStatus === 'error' ? 'bg-red-500' : 'bg-gray-500'
                                    }`}></div>
                                    <span className="text-xs text-gray-500">
                                      {connectionStatus === 'connected' ? '已连接' :
                                       connectionStatus === 'connecting' ? '连接中' :
                                       connectionStatus === 'error' ? '连接错误' : '未连接'}
                                    </span>
                                  </div>
                                )}
                              </div>
                            </div>
                          </div>
                        )}
                      </div>
                    )}
                  </CardContent>

                  <div className="border-t p-4">
                    <div className="space-y-2">
                      <div className="flex items-center space-x-2">
                        <Label htmlFor="errorInfo" className="text-sm whitespace-nowrap">错误信息: <span className="text-red-500">*</span></Label>
                        <Input
                          id="errorInfo"
                          placeholder="请输入错误信息（必填）"
                          value={errorInfo}
                          onChange={(e) => setErrorInfo(e.target.value)}
                          className="flex-1"
                          disabled={sendingMessage || aiThinking}
                          required
                        />
                      </div>
                      
                      <div className="flex space-x-2">
                        <Textarea
                          placeholder={aiThinking ? "AI正在思考中，请稍候..." : "输入您的消息..."}
                          value={newMessage}
                          onChange={(e) => setNewMessage(e.target.value)}
                          className="flex-1 min-h-[60px] resize-none"
                          onKeyPress={(e) => {
                            if (e.key === 'Enter' && !e.shiftKey && !aiThinking) {
                              e.preventDefault();
                              handleSendMessage();
                            }
                          }}
                          disabled={sendingMessage || aiThinking}
                        />
                        <Button 
                          onClick={handleSendMessage} 
                          className="self-end"
                          disabled={sendingMessage || !newMessage.trim() || aiThinking || !errorInfo.trim()}
                        >
                          {sendingMessage || aiThinking ? (
                            <Loader2 className="w-4 h-4 animate-spin" />
                          ) : (
                            <Send className="w-4 h-4" />
                          )}
                        </Button>
                      </div>
                    </div>
                    <div className="flex items-center justify-between mt-2 text-xs text-gray-500">
                      {aiThinking ? (
                        <span className="text-amber-600">
                          {isStreaming ? '正在接收流式响应...' : `AI正在思考中，已用时 ${aiThinkingTime} 秒，请耐心等待...`}
                        </span>
                      ) : (
                        <span>按 Enter 发送，Shift + Enter 换行 | 支持流式响应</span>
                      )}
                    </div>
                  </div>
                </>
              ) : (
                <div className="flex items-center justify-center h-full text-gray-500">
                  <div className="text-center">
                    <MessageSquare className="w-16 h-16 mx-auto mb-4 text-gray-300" />
                    <p className="text-lg font-medium">选择一个对话</p>
                    <p className="text-sm">从左侧列表中选择对话开始聊天</p>
                  </div>
                </div>
              )}
            </Card>
          </div>

          <div className="lg:col-span-1">
            <div className="space-y-4">
              {selectedSession && (
                <>
                  <Card>
                    <CardHeader>
                      <CardTitle className="text-lg">对话信息</CardTitle>
                    </CardHeader>
                    <CardContent className="space-y-4">
                      <div className="flex items-center justify-between">
                        <span className="text-sm text-gray-600">消息总数</span>
                        <span className="font-medium">{selectedSession.message_count}</span>
                      </div>
                      <div className="flex items-center justify-between">
                        <span className="text-sm text-gray-600">创建时间</span>
                        <span className="font-medium text-sm">
                          {formatTime(selectedSession.created_at)}
                        </span>
                      </div>
                      <div className="flex items-center justify-between">
                        <span className="text-sm text-gray-600">最后活动</span>
                        <span className="font-medium text-sm">
                          {formatTime(selectedSession.last_message_at || selectedSession.updated_at)}
                        </span>
                      </div>
                      <div className="flex items-center justify-between">
                        <span className="text-sm text-gray-600">状态</span>
                        {getStatusBadge(selectedSession.status)}
                      </div>
                      {aiThinking && (
                        <div className="flex items-center justify-between">
                          <span className="text-sm text-amber-600">AI思考时间</span>
                          <span className="font-medium text-amber-600">{aiThinkingTime} 秒</span>
                        </div>
                      )}
                      {connectionStatus !== 'disconnected' && (
                        <div className="flex items-center justify-between">
                          <span className="text-sm text-gray-600">连接状态</span>
                          <div className="flex items-center space-x-1">
                            <div className={`w-2 h-2 rounded-full ${
                              connectionStatus === 'connected' ? 'bg-green-500' :
                              connectionStatus === 'connecting' ? 'bg-yellow-500' :
                              connectionStatus === 'error' ? 'bg-red-500' : 'bg-gray-500'
                            }`}></div>
                            <span className="text-xs">
                              {connectionStatus === 'connected' ? '已连接' :
                               connectionStatus === 'connecting' ? '连接中' :
                               connectionStatus === 'error' ? '连接错误' : '未连接'}
                            </span>
                          </div>
                        </div>
                      )}
                    </CardContent>
                  </Card>

                  <Card>
                    <CardHeader>
                      <CardTitle className="text-lg">快速操作</CardTitle>
                    </CardHeader>
                    <CardContent className="space-y-2">
                      <Button variant="outline" className="w-full justify-start" onClick={handleExportChat}>
                        <Download className="w-4 h-4 mr-2" />
                        导出聊天记录
                      </Button>
                      <Button 
                        variant="outline" 
                        className="w-full justify-start text-blue-600 hover:text-blue-700"
                        onClick={() => selectedSession && openFeedbackDialog(selectedSession.session_id)}
                      >
                        <MessageSquare className="w-4 h-4 mr-2" />
                        评价此对话
                      </Button>
                      <Button 
                        variant="outline" 
                        className="w-full justify-start text-red-600 hover:text-red-700"
                        onClick={() => selectedSession && handleDeleteSession(selectedSession.session_id)}
                      >
                        <Trash2 className="w-4 h-4 mr-2" />
                        删除当前对话
                      </Button>
                      <Button 
                        variant={showUserMonitor ? "default" : "outline"}
                        className="w-full justify-start text-purple-600 hover:text-purple-700"
                        onClick={() => setShowUserMonitor(!showUserMonitor)}
                      >
                        <Users className="w-4 h-4 mr-2" />
                        {showUserMonitor ? '隐藏用户监控' : '显示用户监控'}
                      </Button>
                      <Button 
                        variant={showBotConfig ? "default" : "outline"}
                        className="w-full justify-start text-blue-600 hover:text-blue-700"
                        onClick={() => setShowBotConfig(!showBotConfig)}
                      >
                        <Bot className="w-4 h-4 mr-2" />
                        {showBotConfig ? '隐藏机器人配置' : '显示机器人配置'}
                      </Button>
                      <Button 
                        variant={showAnalytics ? "default" : "outline"}
                        className="w-full justify-start text-green-600 hover:text-green-700"
                        onClick={() => setShowAnalytics(!showAnalytics)}
                      >
                        <BarChart3 className="w-4 h-4 mr-2" />
                        {showAnalytics ? '隐藏数据统计' : '显示数据统计'}
                      </Button>
                      <Button 
                        variant={showContentFilter ? "default" : "outline"}
                        className="w-full justify-start text-purple-600 hover:text-purple-700"
                        onClick={() => setShowContentFilter(!showContentFilter)}
                      >
                        <Eye className="w-4 h-4 mr-2" />
                        {showContentFilter ? '隐藏内容审核' : '显示内容审核'}
                      </Button>
                    </CardContent>
                  </Card>
                </>
              )}

              <Card>
                <CardHeader>
                  <CardTitle className="text-lg">系统状态</CardTitle>
                </CardHeader>
                <CardContent className="space-y-3">
                  <div className="flex items-center justify-between">
                    <span className="text-sm text-gray-600">总对话数</span>
                    <span className="font-medium">{sessions.length}</span>
                  </div>
                  <div className="flex items-center justify-between">
                    <span className="text-sm text-gray-600">活跃对话</span>
                    <span className="font-medium">
                      {sessions.filter(s => s.status === 'active').length}
                    </span>
                  </div>
                  <div className="flex items-center justify-between">
                    <span className="text-sm text-gray-600">待处理</span>
                    <span className="font-medium">
                      {sessions.filter(s => s.status === 'pending').length}
                    </span>
                  </div>
                  {aiThinking && (
                    <div className="mt-4 p-2 bg-amber-50 rounded-md border border-amber-200">
                      <p className="text-sm text-amber-700 font-medium">
                        {isStreaming ? 'AI正在流式响应' : 'AI正在处理请求'}
                      </p>
                      <p className="text-xs text-amber-600 mt-1">
                        已用时 {aiThinkingTime} 秒
                        {aiThinkingTime > 300 && " (长时间请求可能需要10分钟)"}
                      </p>
                      {connectionStatus !== 'disconnected' && (
                        <div className="flex items-center space-x-1 mt-1">
                          <div className={`w-2 h-2 rounded-full ${
                            connectionStatus === 'connected' ? 'bg-green-500' :
                            connectionStatus === 'connecting' ? 'bg-yellow-500' :
                            connectionStatus === 'error' ? 'bg-red-500' : 'bg-gray-500'
                          }`}></div>
                          <span className="text-xs text-amber-600">
                            流式连接: {connectionStatus === 'connected' ? '已连接' :
                                     connectionStatus === 'connecting' ? '连接中' :
                                     connectionStatus === 'error' ? '连接错误' : '未连接'}
                          </span>
                        </div>
                      )}
                    </div>
                  )}
                </CardContent>
              </Card>
            </div>
          </div>
        </div>
      </div>

      {/* 导出对话框 */}
      <Dialog open={showExportDialog} onOpenChange={setShowExportDialog}>
        <DialogContent className="sm:max-w-md">
          <DialogHeader>
            <DialogTitle>导出聊天记录</DialogTitle>
            <DialogDescription>
              选择导出格式并下载聊天记录
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-4">
            <div className="space-y-2">
              <Label htmlFor="export-format">导出格式</Label>
              <Select value={exportFormat} onValueChange={setExportFormat}>
                <SelectTrigger>
                  <SelectValue placeholder="选择导出格式" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="text">文本格式 (.txt)</SelectItem>
                  <SelectItem value="pdf">PDF格式 (.pdf)</SelectItem>
                </SelectContent>
              </Select>
            </div>
          </div>
          <DialogFooter className="flex justify-end space-x-2">
            <Button
              variant="outline"
              onClick={() => setShowExportDialog(false)}
              disabled={exportLoading}
            >
              取消
            </Button>
            <Button
              onClick={handleExport}
              disabled={exportLoading || !exportFormat}
            >
              {exportLoading ? (
                <>
                  <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                  导出中...
                </>
              ) : (
                <>
                  <Download className="w-4 h-4 mr-2" />
                  导出
                </>
              )}
            </Button>
          </DialogFooter>
         </DialogContent>
       </Dialog>

       {/* 反馈对话框 */}
       <Dialog open={showFeedbackDialog} onOpenChange={setShowFeedbackDialog}>
         <DialogContent className="sm:max-w-md">
           <DialogHeader>
             <DialogTitle>评价和反馈</DialogTitle>
             <DialogDescription>
               {feedbackMessageId ? '为这条AI回复评分并提供反馈' : '为整个对话评分并提供反馈'}
             </DialogDescription>
           </DialogHeader>
           <div className="space-y-4">
             {/* 评分区域 */}
             <div className="space-y-2">
               <Label>整体评分 <span className="text-red-500">*</span></Label>
               <div className="flex items-center space-x-2">
                 {[1, 2, 3, 4, 5].map((star) => (
                   <button
                     key={star}
                     onClick={() => setRating(star)}
                     className={`w-8 h-8 text-2xl transition-colors ${
                       rating >= star
                         ? 'text-yellow-400 hover:text-yellow-500'
                         : 'text-gray-300 hover:text-yellow-300'
                     }`}
                   >
                     ★
                   </button>
                 ))}
                 <span className="ml-2 text-sm text-gray-600">
                   {rating > 0 && `${rating} 星`}
                 </span>
               </div>
             </div>

             {/* 反馈类别 */}
             <div className="space-y-2">
               <Label htmlFor="feedback-category">反馈类别</Label>
               <Select value={feedbackCategory} onValueChange={setFeedbackCategory}>
                 <SelectTrigger>
                   <SelectValue placeholder="选择反馈类别" />
                 </SelectTrigger>
                 <SelectContent>
                   <SelectItem value="helpful">有用性</SelectItem>
                   <SelectItem value="accurate">准确性</SelectItem>
                   <SelectItem value="relevant">相关性</SelectItem>
                   <SelectItem value="clear">清晰度</SelectItem>
                   <SelectItem value="other">其他</SelectItem>
                 </SelectContent>
               </Select>
             </div>

             {/* 详细反馈 */}
             <div className="space-y-2">
               <Label htmlFor="feedback-text">详细反馈（可选）</Label>
               <Textarea
                 id="feedback-text"
                 placeholder="请描述您的具体反馈和建议..."
                 value={feedbackText}
                 onChange={(e) => setFeedbackText(e.target.value)}
                 className="min-h-[80px] resize-none"
                 disabled={submittingFeedback}
               />
             </div>
           </div>
           <DialogFooter className="flex justify-end space-x-2">
             <Button
               variant="outline"
               onClick={() => setShowFeedbackDialog(false)}
               disabled={submittingFeedback}
             >
               取消
             </Button>
             <Button
               onClick={submitFeedback}
               disabled={submittingFeedback || rating === 0}
             >
               {submittingFeedback ? (
                 <>
                   <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                   提交中...
                 </>
               ) : (
                 <>
                   <MessageSquare className="w-4 h-4 mr-2" />
                   提交反馈
                 </>
               )}
             </Button>
           </DialogFooter>
         </DialogContent>
       </Dialog>

       {/* 用户监控面板 */}
       {showUserMonitor && (
         <Card className="mt-4">
           <CardHeader>
             <CardTitle className="text-lg flex items-center">
               <Users className="w-5 h-5 mr-2" />
               在线用户监控
             </CardTitle>
           </CardHeader>
           <CardContent>
             <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
               {onlineUsers.map((user) => (
                 <div key={user.id} className="border rounded-lg p-4 space-y-3">
                   <div className="flex items-center justify-between">
                     <div className="flex items-center space-x-2">
                       <div className={`w-3 h-3 rounded-full ${getUserStatusColor(user.status)}`}></div>
                       <span className="font-medium">{user.name}</span>
                     </div>
                     <span className={`text-xs px-2 py-1 rounded-full ${
                       user.status === 'online' ? 'bg-green-100 text-green-800' :
                       user.status === 'busy' ? 'bg-red-100 text-red-800' :
                       user.status === 'away' ? 'bg-yellow-100 text-yellow-800' :
                       'bg-gray-100 text-gray-800'
                     }`}>
                       {getUserStatusText(user.status)}
                     </span>
                   </div>
                   
                   <div className="text-sm text-gray-600 space-y-1">
                     <div className="flex justify-between">
                       <span>角色:</span>
                       <span className="font-medium">{user.role}</span>
                     </div>
                     <div className="flex justify-between">
                       <span>当前会话:</span>
                       <span className="font-medium">{userWorkload[user.id] || 0}</span>
                     </div>
                     <div className="flex justify-between">
                       <span>最后活动:</span>
                       <span className="font-medium">{formatTime(user.lastActivity)}</span>
                     </div>
                   </div>

                   {/* 用户分配的会话列表 */}
                   {userSessions[user.id] && userSessions[user.id].length > 0 && (
                     <div className="space-y-2">
                       <div className="text-sm font-medium text-gray-700">分配的会话:</div>
                       <div className="space-y-1 max-h-32 overflow-y-auto">
                         {userSessions[user.id].map((sessionId) => {
                           const session = sessions.find(s => s.session_id === sessionId);
                           return session ? (
                             <div key={sessionId} className="text-xs p-2 bg-gray-50 rounded flex items-center justify-between">
                               <span className="truncate">{session.title}</span>
                               <span className={`px-1 py-0.5 rounded text-xs ${
                                 session.status === 'active' ? 'bg-green-100 text-green-700' :
                                 session.status === 'pending' ? 'bg-yellow-100 text-yellow-700' :
                                 'bg-gray-100 text-gray-700'
                               }`}>
                                 {session.status === 'active' ? '活跃' :
                                  session.status === 'pending' ? '待处理' : '已归档'}
                               </span>
                             </div>
                           ) : null;
                         })}
                       </div>
                     </div>
                   )}
                 </div>
               ))}
             </div>
           </CardContent>
         </Card>
       )}

       {/* 会话分配对话框 */}
       <Dialog open={showAssignDialog} onOpenChange={setShowAssignDialog}>
         <DialogContent className="sm:max-w-md">
           <DialogHeader>
             <DialogTitle>分配会话</DialogTitle>
             <DialogDescription>
               选择要分配给的用户
             </DialogDescription>
           </DialogHeader>
           <div className="space-y-4">
             <div className="space-y-2">
               <Label>选择用户</Label>
               <div className="space-y-2 max-h-64 overflow-y-auto">
                 {onlineUsers.filter(user => user.status !== 'offline').map((user) => (
                   <div
                     key={user.id}
                     className={`p-3 border rounded-lg cursor-pointer transition-colors ${
                       selectedUser === user.id
                         ? 'border-blue-500 bg-blue-50'
                         : 'border-gray-200 hover:border-gray-300'
                     }`}
                     onClick={() => setSelectedUser(user.id)}
                   >
                     <div className="flex items-center justify-between">
                       <div className="flex items-center space-x-2">
                         <div className={`w-2 h-2 rounded-full ${getUserStatusColor(user.status)}`}></div>
                         <span className="font-medium">{user.name}</span>
                         <span className="text-sm text-gray-500">({user.role})</span>
                       </div>
                       <div className="text-sm text-gray-600">
                         {userWorkload[user.id] || 0} 个会话
                       </div>
                     </div>
                   </div>
                 ))}
               </div>
             </div>
           </div>
           <DialogFooter className="flex justify-end space-x-2">
             <Button
               variant="outline"
               onClick={() => {
                 setShowAssignDialog(false);
                 setSelectedUser('');
                 setAssignSessionId('');
               }}
             >
               取消
             </Button>
             <Button
               onClick={() => assignSessionToUser(assignSessionId, selectedUser)}
               disabled={!selectedUser}
             >
               <Users className="w-4 h-4 mr-2" />
               分配
             </Button>
           </DialogFooter>
         </DialogContent>
       </Dialog>

       {/* 机器人配置面板 */}
       {showBotConfig && (
         <Card className="mt-4">
           <CardHeader>
             <CardTitle className="text-lg flex items-center justify-between">
               <div className="flex items-center">
                 <Bot className="w-5 h-5 mr-2" />
                 机器人配置管理
               </div>
               <Button
                 size="sm"
                 onClick={() => openConfigDialog()}
               >
                 <Plus className="w-4 h-4 mr-2" />
                 新建配置
               </Button>
             </CardTitle>
           </CardHeader>
           <CardContent>
             <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
               {botConfigs.map((config) => (
                 <div key={config.id} className="border rounded-lg p-4 space-y-3">
                   <div className="flex items-center justify-between">
                     <div className="flex items-center space-x-2">
                       <div className={`w-3 h-3 rounded-full ${
                         config.isActive ? 'bg-green-500' : 'bg-gray-400'
                       }`}></div>
                       <span className="font-medium">{config.name}</span>
                     </div>
                     <div className="flex items-center space-x-1">
                       <Button
                         size="sm"
                         variant="ghost"
                         onClick={() => toggleBotActive(config.id)}
                       >
                         {config.isActive ? (
                           <Pause className="w-4 h-4" />
                         ) : (
                           <Play className="w-4 h-4" />
                         )}
                       </Button>
                       <Button
                         size="sm"
                         variant="ghost"
                         onClick={() => openConfigDialog(config)}
                       >
                         <Settings className="w-4 h-4" />
                       </Button>
                       <Button
                         size="sm"
                         variant="ghost"
                         onClick={() => deleteBotConfig(config.id)}
                       >
                         <Trash2 className="w-4 h-4" />
                       </Button>
                     </div>
                   </div>
                   
                   <div className="text-sm text-gray-600 space-y-1">
                     <div className="flex justify-between">
                       <span>模型:</span>
                       <span className="font-medium">{config.model}</span>
                     </div>
                     <div className="flex justify-between">
                       <span>温度:</span>
                       <span className="font-medium">{config.temperature}</span>
                     </div>
                     <div className="flex justify-between">
                       <span>最大令牌:</span>
                       <span className="font-medium">{config.maxTokens}</span>
                     </div>
                     <div className="flex justify-between">
                       <span>训练状态:</span>
                       <span className={`font-medium ${
                         config.trainingStatus === 'completed' ? 'text-green-600' :
                         config.trainingStatus === 'training' ? 'text-blue-600' :
                         config.trainingStatus === 'failed' ? 'text-red-600' :
                         'text-gray-600'
                       }`}>
                         {config.trainingStatus === 'completed' ? '已完成' :
                          config.trainingStatus === 'training' ? '训练中' :
                          config.trainingStatus === 'failed' ? '失败' : '未训练'}
                       </span>
                     </div>
                   </div>

                   <div className="text-xs text-gray-500 truncate">
                     {config.description || '暂无描述'}
                   </div>

                   <div className="flex space-x-2">
                     <Button
                       size="sm"
                       variant="outline"
                       className="flex-1"
                       onClick={() => openTrainingDialog(config)}
                       disabled={config.trainingStatus === 'training'}
                     >
                       <Brain className="w-4 h-4 mr-1" />
                       {config.trainingStatus === 'training' ? '训练中' : '训练'}
                     </Button>
                   </div>
                 </div>
               ))}
             </div>
           </CardContent>
         </Card>
       )}

       {/* 机器人配置对话框 */}
       <Dialog open={showConfigDialog} onOpenChange={setShowConfigDialog}>
         <DialogContent className="sm:max-w-lg">
           <DialogHeader>
             <DialogTitle>
               {selectedBotConfig ? '编辑机器人配置' : '新建机器人配置'}
             </DialogTitle>
             <DialogDescription>
               配置机器人的基本参数和行为设置
             </DialogDescription>
           </DialogHeader>
           <div className="space-y-4">
             <div className="space-y-2">
               <Label htmlFor="config-name">配置名称 <span className="text-red-500">*</span></Label>
               <Input
                 id="config-name"
                 placeholder="输入配置名称"
                 value={configForm.name}
                 onChange={(e) => setConfigForm({...configForm, name: e.target.value})}
               />
             </div>
             
             <div className="space-y-2">
               <Label htmlFor="config-model">AI模型</Label>
               <Select value={configForm.model} onValueChange={(value) => setConfigForm({...configForm, model: value})}>
                 <SelectTrigger>
                   <SelectValue placeholder="选择AI模型" />
                 </SelectTrigger>
                 <SelectContent>
                   <SelectItem value="gpt-3.5-turbo">GPT-3.5 Turbo</SelectItem>
                   <SelectItem value="gpt-4">GPT-4</SelectItem>
                   <SelectItem value="claude-3">Claude-3</SelectItem>
                   <SelectItem value="gemini-pro">Gemini Pro</SelectItem>
                 </SelectContent>
               </Select>
             </div>

             <div className="grid grid-cols-2 gap-4">
               <div className="space-y-2">
                 <Label htmlFor="config-temperature">温度 (0-1)</Label>
                 <Input
                   id="config-temperature"
                   type="number"
                   min="0"
                   max="1"
                   step="0.1"
                   placeholder="0.7"
                   value={configForm.temperature}
                   onChange={(e) => setConfigForm({...configForm, temperature: parseFloat(e.target.value) || 0})}
                 />
               </div>
               
               <div className="space-y-2">
                 <Label htmlFor="config-tokens">最大令牌数</Label>
                 <Input
                   id="config-tokens"
                   type="number"
                   min="1"
                   max="4096"
                   placeholder="2048"
                   value={configForm.maxTokens}
                   onChange={(e) => setConfigForm({...configForm, maxTokens: parseInt(e.target.value) || 0})}
                 />
               </div>
             </div>

             <div className="space-y-2">
               <Label htmlFor="config-prompt">系统提示词</Label>
               <Textarea
                 id="config-prompt"
                 placeholder="输入系统提示词，定义机器人的角色和行为..."
                 value={configForm.systemPrompt}
                 onChange={(e) => setConfigForm({...configForm, systemPrompt: e.target.value})}
                 className="min-h-[100px] resize-none"
               />
             </div>

             <div className="space-y-2">
               <Label htmlFor="config-description">描述（可选）</Label>
               <Textarea
                 id="config-description"
                 placeholder="描述这个配置的用途和特点..."
                 value={configForm.description}
                 onChange={(e) => setConfigForm({...configForm, description: e.target.value})}
                 className="min-h-[60px] resize-none"
               />
             </div>
           </div>
           <DialogFooter className="flex justify-end space-x-2">
             <Button
               variant="outline"
               onClick={() => {
                 setShowConfigDialog(false);
                 setSelectedBotConfig(null);
                 setConfigForm({
                   name: '',
                   model: 'gpt-3.5-turbo',
                   temperature: 0.7,
                   maxTokens: 2048,
                   systemPrompt: '',
                   description: ''
                 });
               }}
             >
               取消
             </Button>
             <Button
               onClick={() => saveBotConfig()}
               disabled={!configForm.name.trim()}
             >
               <Save className="w-4 h-4 mr-2" />
               {selectedBotConfig ? '更新配置' : '创建配置'}
             </Button>
           </DialogFooter>
         </DialogContent>
       </Dialog>

       {/* 机器人训练对话框 */}
       <Dialog open={showTrainingDialog} onOpenChange={setShowTrainingDialog}>
         <DialogContent className="sm:max-w-lg">
           <DialogHeader>
             <DialogTitle>训练机器人</DialogTitle>
             <DialogDescription>
               为 {selectedBotConfig?.name} 提供训练数据
             </DialogDescription>
           </DialogHeader>
           <div className="space-y-4">
             <div className="space-y-2">
               <Label htmlFor="training-data">训练数据 <span className="text-red-500">*</span></Label>
               <Textarea
                 id="training-data"
                 placeholder="输入训练数据，每行一个问答对，格式：问题|答案"
                 value={trainingData}
                 onChange={(e) => setTrainingData(e.target.value)}
                 className="min-h-[200px] resize-none font-mono text-sm"
               />
               <div className="text-xs text-gray-500">
                 示例格式：<br/>
                 你好|您好！我是AI助手，很高兴为您服务。<br/>
                 公司地址在哪里|我们公司位于北京市朝阳区...
               </div>
             </div>

             {trainingStatus === 'training' && (
               <div className="space-y-2">
                 <div className="flex items-center justify-between">
                   <span className="text-sm font-medium">训练进度</span>
                   <span className="text-sm text-gray-600">{trainingProgress}%</span>
                 </div>
                 <div className="w-full bg-gray-200 rounded-full h-2">
                   <div 
                     className="bg-blue-600 h-2 rounded-full transition-all duration-300"
                     style={{ width: `${trainingProgress}%` }}
                   ></div>
                 </div>
               </div>
             )}
           </div>
           <DialogFooter className="flex justify-end space-x-2">
             <Button
               variant="outline"
               onClick={() => {
                 setShowTrainingDialog(false);
                 setSelectedBotConfig(null);
                 setTrainingData('');
                 setTrainingStatus('idle');
                 setTrainingProgress(0);
               }}
               disabled={trainingStatus === 'training'}
             >
               {trainingStatus === 'training' ? '训练中...' : '取消'}
             </Button>
             <Button
               onClick={() => startTraining()}
               disabled={!trainingData.trim() || trainingStatus === 'training'}
             >
               {trainingStatus === 'training' ? (
                 <>
                   <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                   训练中...
                 </>
               ) : (
                 <>
                   <Brain className="w-4 h-4 mr-2" />
                   开始训练
                 </>
               )}
             </Button>
           </DialogFooter>
         </DialogContent>
       </Dialog>

       {/* 数据统计面板 */}
       {showAnalytics && (
         <Card className="mt-6">
           <CardHeader>
             <div className="flex items-center justify-between">
               <CardTitle className="text-lg flex items-center">
                 <BarChart3 className="w-5 h-5 mr-2" />
                 聊天数据统计分析
               </CardTitle>
               <div className="flex items-center space-x-2">
                 <Select value={analyticsTimeRange} onValueChange={setAnalyticsTimeRange}>
                   <SelectTrigger className="w-32">
                     <SelectValue />
                   </SelectTrigger>
                   <SelectContent>
                     <SelectItem value="today">今天</SelectItem>
                     <SelectItem value="week">本周</SelectItem>
                     <SelectItem value="month">本月</SelectItem>
                     <SelectItem value="quarter">本季度</SelectItem>
                   </SelectContent>
                 </Select>
                 <Button
                   variant="outline"
                   size="sm"
                   onClick={refreshAnalytics}
                   disabled={analyticsLoading}
                 >
                   {analyticsLoading ? (
                     <Loader2 className="w-4 h-4 animate-spin" />
                   ) : (
                     <RefreshCw className="w-4 h-4" />
                   )}
                 </Button>
                 <Button
                   variant="outline"
                   size="sm"
                   onClick={() => setShowExportDialog(true)}
                 >
                   <Download className="w-4 h-4 mr-2" />
                   导出数据
                 </Button>
               </div>
             </div>
           </CardHeader>
           <CardContent>
             {analyticsLoading ? (
               <div className="flex items-center justify-center py-8">
                 <Loader2 className="w-6 h-6 animate-spin mr-2" />
                 <span>加载统计数据中...</span>
               </div>
             ) : (
               <div className="space-y-6">
                 {/* 概览统计 */}
                 <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
                   <div className="bg-blue-50 p-4 rounded-lg border border-blue-200">
                     <div className="flex items-center justify-between">
                       <div>
                         <p className="text-sm text-blue-600 font-medium">总对话数</p>
                         <p className="text-2xl font-bold text-blue-700">{analyticsData.totalSessions}</p>
                       </div>
                       <MessageSquare className="w-8 h-8 text-blue-500" />
                     </div>
                   </div>
                   
                   <div className="bg-green-50 p-4 rounded-lg border border-green-200">
                     <div className="flex items-center justify-between">
                       <div>
                         <p className="text-sm text-green-600 font-medium">总消息数</p>
                         <p className="text-2xl font-bold text-green-700">{analyticsData.totalMessages}</p>
                       </div>
                       <Send className="w-8 h-8 text-green-500" />
                     </div>
                   </div>
                   
                   <div className="bg-purple-50 p-4 rounded-lg border border-purple-200">
                     <div className="flex items-center justify-between">
                       <div>
                         <p className="text-sm text-purple-600 font-medium">活跃用户</p>
                         <p className="text-2xl font-bold text-purple-700">{analyticsData.activeUsers}</p>
                       </div>
                       <Users className="w-8 h-8 text-purple-500" />
                     </div>
                   </div>
                   
                   <div className="bg-orange-50 p-4 rounded-lg border border-orange-200">
                     <div className="flex items-center justify-between">
                       <div>
                         <p className="text-sm text-orange-600 font-medium">平均响应时间</p>
                         <p className="text-2xl font-bold text-orange-700">{analyticsData.avgResponseTime}s</p>
                       </div>
                       <Clock className="w-8 h-8 text-orange-500" />
                     </div>
                   </div>
                 </div>

                 {/* 详细统计表格 */}
                 <div className="space-y-4">
                   <h3 className="text-lg font-semibold">详细统计</h3>
                   <div className="border rounded-lg overflow-hidden">
                     <table className="w-full">
                       <thead className="bg-gray-50">
                         <tr>
                           <th className="px-4 py-3 text-left text-sm font-medium text-gray-700">指标</th>
                           <th className="px-4 py-3 text-left text-sm font-medium text-gray-700">数值</th>
                           <th className="px-4 py-3 text-left text-sm font-medium text-gray-700">趋势</th>
                         </tr>
                       </thead>
                       <tbody className="divide-y divide-gray-200">
                         <tr>
                           <td className="px-4 py-3 text-sm text-gray-900">用户满意度</td>
                           <td className="px-4 py-3 text-sm text-gray-900">{analyticsData.satisfaction}%</td>
                           <td className="px-4 py-3 text-sm text-green-600">↗ +2.3%</td>
                         </tr>
                         <tr>
                           <td className="px-4 py-3 text-sm text-gray-900">问题解决率</td>
                           <td className="px-4 py-3 text-sm text-gray-900">{analyticsData.resolutionRate}%</td>
                           <td className="px-4 py-3 text-sm text-green-600">↗ +1.8%</td>
                         </tr>
                         <tr>
                           <td className="px-4 py-3 text-sm text-gray-900">平均对话轮数</td>
                           <td className="px-4 py-3 text-sm text-gray-900">{analyticsData.avgTurns}</td>
                           <td className="px-4 py-3 text-sm text-red-600">↘ -0.5</td>
                         </tr>
                         <tr>
                           <td className="px-4 py-3 text-sm text-gray-900">热门话题</td>
                           <td className="px-4 py-3 text-sm text-gray-900">{analyticsData.topTopics.join(', ')}</td>
                           <td className="px-4 py-3 text-sm text-gray-500">-</td>
                         </tr>
                       </tbody>
                     </table>
                   </div>
                 </div>
               </div>
             )}
           </CardContent>
         </Card>
       )}

       {/* 审核日志导出对话框 */}
       <Dialog open={showAuditDialog} onOpenChange={setShowAuditDialog}>
         <DialogContent className="sm:max-w-md">
           <DialogHeader>
             <DialogTitle>导出审核日志</DialogTitle>
             <DialogDescription>
               选择导出格式和时间范围
             </DialogDescription>
           </DialogHeader>
           <div className="space-y-4">
             <div className="space-y-2">
               <Label htmlFor="audit-export-format">导出格式</Label>
               <Select value={exportFormat} onValueChange={setExportFormat}>
                 <SelectTrigger>
                   <SelectValue placeholder="选择导出格式" />
                 </SelectTrigger>
                 <SelectContent>
                   <SelectItem value="csv">CSV格式 (.csv)</SelectItem>
                   <SelectItem value="json">JSON格式 (.json)</SelectItem>
                   <SelectItem value="excel">Excel格式 (.xlsx)</SelectItem>
                 </SelectContent>
               </Select>
             </div>
             
             <div className="space-y-2">
               <Label htmlFor="audit-date-range">时间范围</Label>
               <Select value={exportDateRange} onValueChange={setExportDateRange}>
                 <SelectTrigger>
                   <SelectValue placeholder="选择时间范围" />
                 </SelectTrigger>
                 <SelectContent>
                   <SelectItem value="today">今天</SelectItem>
                   <SelectItem value="week">本周</SelectItem>
                   <SelectItem value="month">本月</SelectItem>
                   <SelectItem value="quarter">本季度</SelectItem>
                   <SelectItem value="year">本年</SelectItem>
                 </SelectContent>
               </Select>
             </div>
           </div>
           <DialogFooter className="flex justify-end space-x-2">
             <Button
               variant="outline"
               onClick={() => {
                 setShowAuditDialog(false);
                 setExportFormat('csv');
                 setExportDateRange('month');
               }}
             >
               取消
             </Button>
             <Button
               onClick={exportAuditLogs}
               disabled={!exportFormat || !exportDateRange}
             >
               <Download className="w-4 h-4 mr-2" />
               导出日志
             </Button>
           </DialogFooter>
         </DialogContent>
       </Dialog>

       {/* 统计数据导出对话框 */}
       <Dialog open={showExportDialog} onOpenChange={setShowExportDialog}>
         <DialogContent className="sm:max-w-md">
           <DialogHeader>
             <DialogTitle>导出统计数据</DialogTitle>
             <DialogDescription>
               选择导出格式和时间范围
             </DialogDescription>
           </DialogHeader>
           <div className="space-y-4">
             <div className="space-y-2">
               <Label htmlFor="export-format">导出格式</Label>
               <Select value={exportFormat} onValueChange={setExportFormat}>
                 <SelectTrigger>
                   <SelectValue placeholder="选择导出格式" />
                 </SelectTrigger>
                 <SelectContent>
                   <SelectItem value="csv">CSV格式 (.csv)</SelectItem>
                   <SelectItem value="json">JSON格式 (.json)</SelectItem>
                   <SelectItem value="excel">Excel格式 (.xlsx)</SelectItem>
                 </SelectContent>
               </Select>
             </div>
             
             <div className="space-y-2">
               <Label htmlFor="export-date-range">时间范围</Label>
               <Select value={exportDateRange} onValueChange={setExportDateRange}>
                 <SelectTrigger>
                   <SelectValue placeholder="选择时间范围" />
                 </SelectTrigger>
                 <SelectContent>
                   <SelectItem value="today">今天</SelectItem>
                   <SelectItem value="week">本周</SelectItem>
                   <SelectItem value="month">本月</SelectItem>
                   <SelectItem value="quarter">本季度</SelectItem>
                   <SelectItem value="year">本年</SelectItem>
                 </SelectContent>
               </Select>
             </div>
           </div>
           <DialogFooter className="flex justify-end space-x-2">
             <Button
               variant="outline"
               onClick={() => {
                 setShowExportDialog(false);
                 setExportFormat('csv');
                 setExportDateRange('month');
               }}
             >
               取消
             </Button>
             <Button
               onClick={exportAnalyticsData}
               disabled={!exportFormat || !exportDateRange}
             >
               <Download className="w-4 h-4 mr-2" />
               导出数据
             </Button>
           </DialogFooter>
         </DialogContent>
       </Dialog>
       
       {/* Token过期重新登录对话框 */}
       <ReauthDialogComponent />
     </div>
   );
 }
